Background
Playing around with elementary Rust Code and found out more about its strong type checking.
Code
Original
/* Declare Struct Person Structure Parts:- name & age */ struct Person { name: String , age: u8 } fn main() { // instantiate structure let objPeter1 = Person { name:"Peter" , age:5 }; }
Output
Output – Image
Output – Text
error[E0308]: mismatched types --> main.rs:18:28 | 18 | name:"Peter" | ^^^^^^^- help: try using a conversion method: `.to_string()` | | | expected struct `String`, found `&str` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`.
Explanation
The error springs from the fact that the Person structure defines the name variable as a string object.
But, we are passing along a string literal.
Definition
String
There are a couple of pathways towards declaring a string in Rust.
Outline
- String Literal(&str)
- String Object(String)
String Literal (&str )
Here are a couple of sample variable string literal declarations:-
let personFirstname = "Walter";
let personMiddleName:&str="l.";
let personLastname:&'static str = "Johnson";
String Object(String)
On the other hand, here are some of the available choices for declaring string objects.
let objStringEmpty = String::new();
let objStringFullname = String::from("Paul Young");
Object Type
Let us try to use introspection to get the types of our variables.
Object Type – Function Declaration
Thankfully Rust By Practice has a working code here:-
/* Rust By Practice Get the type of given variable, return a string representation of the type e.g "i8", "u8", "i32", "u32" https://practice.rs/basic-types/numbers.html */ fn typeOf<T>(_: &T) -> String { format! ( "{}" , std::any::type_name::<T>() ) }
Object Type – Sample Invocation
// Type of Variable - &str println! ( "Variable {0} Type is {1}" , "personLastname" , typeOf(&personLastname) ); // Type of Variable - String println! ( "Variable {0} Type is {1}" , "objStringFullname" , typeOf(&objStringFullname) );
Output
Output – Image
Output – Text
Variable personLastname Type is &str Variable objStringFullname Type is alloc::string::String
Code
Revision
/* Declare Struct Person Structure Parts:- name & age */ struct Person { name: String , age: u8 } fn main() { // instantiate structure /* let objPeter1 = Person { name:"Peter" , age:5 }; */ let objPeterson = Person { // name:"Peterson" name:"Peterson".to_string() , age:5 }; }
Code Simulation
OnlineGDB
- rustStructPrintError.rs
Link
References
- TutorialsPoint
- TutorialsPoint – Rust – String
Link
- TutorialsPoint – Rust – String