Modify the values of struct with out creating Impl


Can I create a structure and modify the values inside structure with out creating an Impl for the structure.

For Example:

Struct Position(u32, u32)

Struct Game {
       position : Position,
       obstacles : HashSet<Position>,
       letterpositions : HashMap<Position, char>

If I want to modify or add any of the values in Game, Should I need to provide Impl to add or remove values in obstacles, letterpositions?


If you declare a field of a struct as pub, users of the struct can access it without methods.

use std::collections::HashSet;
use std::collections::HashMap;

#[derive(Debug, PartialEq, Eq, Hash)]
struct Position(pub u32, pub u32);

struct Game {
    pub position: Position,
    pub obstacles: HashSet<Position>,
    pub letterpositions: HashMap<Position, char>,

fn main() {
    let p = Position(1, 2);
    let g = Game {
        position: p,
        obstacles: HashSet::default(),
        letterpositions: HashMap::default(),
    println!("Hello, world! {}", g.position.0);

Playground link


with out using

#[derive(Debug, PartialEq, Eq, Hash)]

My program shows lots of warnings like

Error message: ‘no method named contains found for type &std::collections::HashSet<Position> in the current scope’

I haven’t explored the above until now. Could you explain about these.


Questions like this will be answered much faster on IRC #rust or #rust-beginners. You are very welcome to join.


For a few, select built-in traits, the derive attribute allows you to tell the compiler to create the impl of these traits automatically.

In this case, we ask the compiler to generate impls for the traits Debug (so we can print the structs to stdout), PartialEq (so we can use ==), as well as Eq and Hash. The latter are necessary for HashSet and HashMap to work.