#how do I create an instance of a struct?

30 messages · Page 1 of 1 (latest)

prisma remnant
#

what error are you getting?

covert dock
#

its not an error I just dont know how to use the struct and how to create an instance of them

prisma remnant
#

User { ... } is how you do it

quasi tree
#

Yeah ... that code above just does it

covert dock
#

so to set values do I just make an instance of the struct and then change the values from the original?

prisma remnant
covert dock
#

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

quasi tree
#

Ah yeah this looks more like a question 😄

blazing hill
#

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

covert dock
#

do I need to put it in main or each function

blazing hill
#

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)

covert dock
#

thanks!

blazing hill
#

You can also use a return value; if you prefer. It does the same thing as the above

covert dock
#

yup, it worked tysm

tough tiger
#

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);
covert dock
left adder
covert dock
#

that makes sense, im new to non oop so that helps