#how do I create an instance of a struct?
30 messages · Page 1 of 1 (latest)
its not an error I just dont know how to use the struct and how to create an instance of them
User { ... } is how you do it
Yeah ... that code above just does it
so to set values do I just make an instance of the struct and then change the values from the original?
yes, that's what your code is already doing
im used to oop which is why its so confusing for me 😆
oh shit
i just realized I pasted in the wrong code 💀
name: String,
hex: String,
}
struct ColorTupleStruct(String, String);
fn classic_c_structs() -> ColorClassicStruct {
let green =
return green
}
fn tuple_structs() -> ColorTupleStruct {
let green =
return green
}
fn main() {
let cl_str = classic_c_structs();
println!("{}", "Classic Struct:");
println!("Name: {}", cl_str.name);
println!("Hex: {}", cl_str.hex);
let tup_str = tuple_structs();
println!("{}", "Tuple Struct:");
println!("Name: {}", tup_str.0);
println!("Hex: {}", tup_str.1);
}
theres the right code
Ah yeah this looks more like a question 😄
Well, in either case, same as your previous one
let mut foo = ColorClassicStruct {
name: "foo".to_string(),
hex: "#000000".to_string()
};
foo.name = "bar".to_string();
mut allows you to set the values in it
StructName {} to create one
do I need to put it in main or each function
You need to initialize your struct inside the functions, then let it return
The functions return an owned value (no reference to borrow from in the arguments)
So you need to make an owned one inside the function so you can return it
A nice simple example would be
fn foo() -> MyStruct {
// instantiate owned MyStruct and return it
MyStruct {
name: "green".to_string(),
hex: "#00FF00".to_string()
}
}
Note the lack of a semicolon ;. When you don't put a semicolon, it'll evaluate to that value
; strictly speaking evaluates to Unit () (which is Rust representation for no value)
thanks!
You can also use a return value; if you prefer. It does the same thing as the above
yup, it worked tysm
some people use Struct::new for that constructor syntax
struct S { x: Param }
impl {
pub fn new (x: Param) -> Self {
Self { x }
}
}
S::new(x);
Thanks, didn’t know that existed
note that there isnt actually a concept of constructors, its just convention to have an associated function called new that makes an instance of it, so you can do Type::new(params)
that makes sense, im new to non oop so that helps