Rust:- Generic – Declaring Function – Underscore Character ( _ )

Background

Always my great bane is stealing code.

Major kleptomania for me is unguarded code online.

 

Rust

Get Type Name

So like WrecksInEffect,  quite a number of weeks ago, I was wrecking into cars like I was at an amusement park with bumper cars.

 

std::any::type_name

Enough knocking heads googled on how to get the type name of a variable in Rust.

 

Sample Code – Stack Overflow

How do I print in Rust the type of a variable?

Link

Code

//You can use the std::any::type_name function. This doesn't need a nightly compiler or an external crate, and the results are quite correct:

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

fn main() {
    let s = "Hello";
    let i = 42;

    print_type_of(&s); // &str
    print_type_of(&i); // i32
    print_type_of(&main); // playground::main
    print_type_of(&print_type_of::<i32>); // playground::print_type_of<i32>
    print_type_of(&{ || "Hi!" }); // playground::main::{{closure}}
}

Explanation
  1. Function Declaration
    • fn print_type_of<T>(_: &T)
      • fn
        • function
      • Function Name
        • print_type_of
      • Generic Type
        • <T>
      • Argument
        • _: &T
          • Variable Name
            • _
          • &T
            • Pass Variable by reference ( & )
  2. Argument 1
    • _: &T
    • Our function does not reference the variable’s value
    • To avoid a warning about unused variables we name the variable using Rust Convention
      • Start variable name with _
      • Use the _ placeholder

 

Sample Code – Self

Outline
    1. Functions
      • type_of
        • Function Declaration
          • fn type_of<T>(_: T) -> &’static str
        • Function Name
          • type_of
        • Generic
          • <T>
        • Variable Name
          • _
        • Return
          • A Variable of Type &’static str 
        • Steps
          • Declare variableType
            • Variable Type:- &’static str
          • Get Variable Type
            • std::any::type_name::<T>()
          • Return variableType
      • print_type_of
        • Function Declaration
          • fn print_type_of<T>(_: T)
        • Function Name
          • print_type_of
        • Generic
          • <T>
        • Variable Name
          • _
        • Variable Type
          • T
        • Steps
          • Print Type of Variable
            •  println! ( "{}" , std::any::type_name::<T>() ); 
      • print_type_of_variable_unused
        • Function Declaration
          • fn print_type_of<T>(var: T)
        • Function Name
          • print_type_of
        • Generic
          • <T>
        • Variable Name
          • var
        • Variable Type
          • T
        • Steps
          • Print Type of Variable
              •  println! ( "{}" , std::any::type_name::<T>() ); 

             

             

Code


//#![allow(unused)]
//#![deny(unused)]

/*
	How do I print in Rust the type of a variable?
	https://stackoverflow.com/questions/21747136/how-do-i-print-in-rust-the-type-of-a-variable
	
*/

/*
    Function:- type_of<T>
*/
fn type_of<T>(_: T) -> &'static str 
{
    let variable_type:&'static str;
    
    variable_type = std::any::type_name::<T>();
    
    return variable_type;
    
}

/*
    Function:- print_type_of<T>
*/
fn print_type_of<T>(_: T)
{
    println!
    (
          "{}"
        , std::any::type_name::<T>()
    );
    
}

/*
    Function:- print_type_of_variable_unused<T>
*/
fn print_type_of_variable_unused<T>(var: T)
{
    
   println!
   (
          "{}"
        , std::any::type_name::<T>()
   );
   
}



/*
    Function:- main
*/
fn main() 
{

    /*
        Declare Variables
    */
	let number_integer:i32 = 10;
	let number_float:f32 = 45f32;
	
	let variable_type:&str;
	
	/*
	    Get Type of Variable
	*/
	variable_type = type_of(number_integer);
	println!("{0}", variable_type);
	
	/*
	    Invoke Function print_type_of
	*/
	print_type_of(number_float);
	
	/*
	    Invoke Function print_type_of_variable_unused
	*/	
	print_type_of_variable_unused(variable_type);
	
}



Advisory

Please comment/uncomment out the directives on top of the source code.

The directives referred to are:-

  1. //#![allow(unused)]
  2. //#![deny(unused)]

 

#![deny(unused)]

Compile Error

Image

Text


error: unused variable: `var`
  --> main.rs:39:37
   |
39 | fn print_type_of_variable_unused<T>(var: T)
   |                                     ^^^ help: if this is intentional, prefix it with an underscore: `_var`
   |
note: the lint level is defined here
  --> main.rs:2:9
   |
2  | #![deny(unused)]
   |         ^^^^^^
   = note: `#[deny(unused_variables)]` implied by `#[deny(unused)]`
error: aborting due to previous error

 

Source Code Online

Onlinegdb

  1. rust_typeof_simple.rs
    Link

 

Summary

In summary, when you see


fn type_of<T>(_: T) -> &'static str

The _ simply means please ignore the non-usage/non-reference of the variable ( _:T )

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s