How do I create an instance of a generic type on a struct?

Just so you know for future questions :slight_smile:

Fun choice of background and font, but it’s generally more useful to post your code as text in a code block.

struct Person<Name, Age> {
    name: Name,
    age: Age,
}

impl Person<String, u32> {
    fn new(self) -> Person<String, u32> {
        Person {
            name: "Default".to_owned(),
            age: 0,
        }
    }
    fn greet(person: &Person<String, f64>) {
        println!("Hello, {}", person.name);
    }
}

This makes for a more consistent reading experience (people here are used to reading these code blocks), it allows copying of the code (so people answering your question can reproduce the error message in case that’s helpful with coming up with an answer), and it even ensures compatibility with other accessibility tooling such as screen readers.

2 Likes