These are chat archives for rust-lang/rust

12th
Nov 2016
Sean Kerr
@seankerr
Nov 12 2016 17:37
@btbvoy You can put them wherever you choose within the src directory. If you 'mod test_mod', it'll get compiled.
Pavel Meledin
@btbvoy
Nov 12 2016 21:41
so if I got it correct - unit tests are forced to be placed next to the code itself which means in src/folder and it was designed this way on purpose. Am I correct ?
Sergey Noskov
@Albibek
Nov 12 2016 21:55
there are also integration tests, that are placed into tests dir and used as if they are external to the code
Pavel Meledin
@btbvoy
Nov 12 2016 21:58

One more question about usage of struct. While playing with rust I wrote a test which just simply compares two identical struct's. For instance:

struct Bar {
    id: String
}

and dummy test looks like this:


#[cfg(test)]
mod tests {
    #[test]
    fn it_works()
    {
        assert_eq!(Bar { id: "1".to_string() }, Bar { id: "1".to_string() });
    }
}

but compiler says this: "field id of struct Bar is private". So the question is: How I suppose to use structs and how to init instances of structs ?

Jonas Platte
@jplatte
Nov 12 2016 22:00
@btbvoy If you want your struct to be instantiable like that from anywhere, you have to mark all the fields as pub (e.g. pub id: String)
Which also means that all fields are accessible from the outside.
If you don't want that (you want to hide implementation details), you'll have to create a function in the struct's impl that instantiates a struct for you, e.g.:
impl Bar {
    fn new(id: String) -> Bar {
        Bar { id: id }
    }
}
And then you write Bar::new("1".to_string()) instead of Bar { id: "1".to_string() }
Pavel Meledin
@btbvoy
Nov 12 2016 22:04
@Albibek thanks. I got the idea. Just used to have tests in separate folder like in Java/Scala for instance. So I thought that it possible in rust is well and also was wondering about idea behind forcing to place tests next to the production code since usually it's a good practice to keep tests separately from production code.
@jplatte aha, I see. Thanks for showing an example :+1: :-)