These are chat archives for rust-lang/rust

19th
Jul 2018
Roman Proskuryakov
@kpp
Jul 19 2018 00:39
I thought you had to make ingrs mut
tsoernes
@tsoernes
Jul 19 2018 00:43
yes, if mut then tanriols solution works
Nopey Nope
@Nopey
Jul 19 2018 01:54
Thanks, @IslandUsurper!
trsh
@trsh
Jul 19 2018 07:56
Hi! I can do push and json string into an object like this > let u: User = serde_json::from_str(j).unwrap();. But what if I have already an serde Value (not str), that I want to push in an object. I have first to convert it to an string and then same?
liyuntao
@liyuntao
Jul 19 2018 10:55
guys, I have a simple silly question. I cannot declare a field with type HashMap<String, Any>. basiclly I want to deserialize json to a struct. but json field is dynamic, which may contains string or array.
Dmitriy
@dpogretskiy
Jul 19 2018 11:01
@liyuntao did you try something like serde_json?
if you really wan't to do it like that, then you can create something like enum JsValue { JsString(String), JsArray(Vec<???>) }, as Any is not a really useful type to deal with
liyuntao
@liyuntao
Jul 19 2018 11:02
@dpogretskiy yeah, but not deep enough.
Dmitriy
@dpogretskiy
Jul 19 2018 11:04
there should be types to deal with deserialized data
liyuntao
@liyuntao
Jul 19 2018 11:04
Just wonder Any in rust seems very different from Object in Java.
Dmitriy
@dpogretskiy
Jul 19 2018 11:05
it's somewhat similar, but no that useful
i guess times of dealing with Object's in java have gone finally :)
check the docs, there are some usage examples
liyuntao
@liyuntao
Jul 19 2018 11:09
@dpogretskiy Thank you very much. I'm going to give it a dig..
tsoernes
@tsoernes
Jul 19 2018 19:10

is there a way to chain inplace functions, e.g.

fn swapLexOrder(mut string: String, mut pairs: Vec<Vec<i32>>) -> String {
    let pairsp: Vec<Vec<i32>> = pairs.iter()
                                     .map(|pair| pair.iter().map(|i| i + 1)
                                                            .collect::<Vec<i32>>()
                                                            .sort_unstable())
                                     .collect::<Vec<Vec<i32>>>()
                                     .sort_unstable_by_key(|li| li[0]);

does not work because sort_unstable() is inplace and returns (), which means that collect doesn't work

Dmitriy
@dpogretskiy
Jul 19 2018 19:12
it's just
map(|pair| {
  let mut v = pair.iter().map(___).collect::<Vec<_>>();
  v.sort_unstable();
  v
})
if sort_unstable() returns () there is no way to chain it, unless you make some trait that does exactly what i wrote
tsoernes
@tsoernes
Jul 19 2018 19:19

Final form:

fn swapLexOrder(mut string: String, mut pairs: Vec<Vec<i32>>) -> String {
    let mut pairsp: Vec<Vec<i32>> = pairs.iter()
                                     .map(|pair| {
                                        let mut v = pair.iter()
                                            .map(|i| i + 1)
                                            .collect::<Vec<i32>>();
                                        v.sort_unstable();
                                        v})
                                     .collect::<Vec<Vec<i32>>>();
    pairsp.sort_unstable_by_key(|li| li[0]);

it works but is a somewhat gnarly expression though, would you allow it in a codebase as is?

Akos Vandra
@axos88
Jul 19 2018 19:22
Hey guys. Any idea why this fails to compile with the message that Debug needs to be implemented by B? To display a Foo, as far as I see, only B::Item should be required to implement it:
#[derive(Debug)]
struct Foo<B: Bar>(B::Item) where B::Item: Debug;


trait Bar {
    type Item;
}

struct ABC();

impl Bar for ABC {
    type Item = String;
}

fn foo<B: Bar>(f: Foo<B>) where <B as Bar>::Item: Debug {
    println!("{:?}", f);
}

fn main() {
    foo(Foo::<ABC>("a".into()));
}
error[E0277]: `B` doesn't implement `std::fmt::Debug`
  --> src/middlewares/authentication.rs:65:22
   |
65 |     println!("{:?}", f);
   |                      ^ `B` cannot be formatted using `:?` because it doesn't implement `std::fmt::Debug`
   |
   = help: the trait `std::fmt::Debug` is not implemented for `B`
   = help: consider adding a `where B: std::fmt::Debug` bound
   = note: required because of the requirements on the impl of `std::fmt::Debug` for `middlewares::authentication::Foo<B>`
   = note: required by `std::fmt::Debug::fmt
James McCoy
@jamessan
Jul 19 2018 19:38
@axos88 You're trying to debug format f, which is type Foo<B>. You would need to use f.0 to format the B::Item
tsoernes
@tsoernes
Jul 19 2018 19:43
where did SortedMap go?
was it removed?
Akos Vandra
@axos88
Jul 19 2018 19:43
@jamessan but in order to format Foo<B> I don’t actually need to format B, only B::Item
since Foo only contains elements of B::Item, not B
Dmitriy
@dpogretskiy
Jul 19 2018 19:47
SortedMap is BTreeMap
and it's indeed sorted
James McCoy
@jamessan
Jul 19 2018 20:00
@axos88 If you add the B: Debug clause to foo as the help: suggests and #[derive(Debug)] on ABC, then it works. You raise a good point though :)
Akos Vandra
@axos88
Jul 19 2018 20:11
@jamessan yeah, in the “real” code, I can’t do that, because I don’t “own” Bar :|
Do you think it’s worth opening an issue about this?
James McCoy
@jamessan
Jul 19 2018 20:11
I'm still pretty new in Rust, so I'd wait for someone else to chime in :)
Lyle Mantooth
@IslandUsurper
Jul 19 2018 20:35
@axos88, but if you do own Foo, I wouldn't derive Debug on it, but impl manually. I'm guessing something in the way the derived impl works assumes B should be Debug.
Akos Vandra
@axos88
Jul 19 2018 21:07
I’m guessing so too, but wondering if it’s a bug or not
tsoernes
@tsoernes
Jul 19 2018 21:09
is there an efficient way to do pop on a HashSet? It does not matter which value is returned.
Dmitriy
@dpogretskiy
Jul 19 2018 21:12
@tsoernes iter().take(1).next() and then just remove it
if it's Some
or just iter().next()
Kiara Rusavi
@rusavi
Jul 19 2018 22:19
hello everyone
i have a small function in which i want to print some info
fn print_info(websites: &Vec<String>) {
    for website in websites {
        thread::spawn(|| {
            println!("{}", website);
        });
    }
}
the compiler gives me this error error[E0621]: explicit lifetime required in the type ofwebsites``
Denis Lisov
@tanriol
Jul 19 2018 22:22
This is not gonna work. You spawn a bunch of threads that will access websites, but have absolutely no guarantees that they all finish before websitescan be dropped or modified.
Kiara Rusavi
@rusavi
Jul 19 2018 22:23
@tanriol i only want the function to return when all threads are finished working
Denis Lisov
@tanriol
Jul 19 2018 22:27
This is not available in the standard library at the moment, but there are some crates that implement this. However, this may be not a good idea, depending on your use case, as spawning a thread per item may be slower than a good thread pool.
Kiara Rusavi
@rusavi
Jul 19 2018 22:28
@tanriol i'am new to rust, i'am tryig to implement it myself, without using crates, so i can understand how it work
Denis Lisov
@tanriol
Jul 19 2018 22:32
The most straightforward way (but not the highest performance) would be to do let website = website.clone() before spawning and make your closure a move closure.
Oh, and you need to collect the JoinHandles that spawn returns and to wait on them before returning if you want to wait until all threads are done.
Kiara Rusavi
@rusavi
Jul 19 2018 22:34
@tanriol like this
fn print_info(websites: &Vec<String>) {
    let mut handles = vec![];

    for website in websites {
        let website = website.clone();

        let handle = thread::spawn(move || {
            println!("{}", website);
        });

        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
}
Denis Lisov
@tanriol
Jul 19 2018 22:36
For example, like this. I'd personally write the first loop in a more functional style instead, but that does not matter :-)
Kiara Rusavi
@rusavi
Jul 19 2018 22:38
@tanriol can you show me how?
Denis Lisov
@tanriol
Jul 19 2018 22:39
Like this
Maybe like this
Kiara Rusavi
@rusavi
Jul 19 2018 22:42
@tanriol this is better :)
thank you
Talden
@Talden
Jul 19 2018 23:27

I'm a Java dev learning some Rust and have an itch to scratch - I'm just not sure how yet.

We have a Java app exposing a restful API. An Angular app consumes this API via a generated TypeScript api-client. We use a build task, via reflection, to scan over the compiled java-app for endpoint information and spit out a .ts file.

I'm able to produce a reasonably complete equivalent API in Rust with Rocket but don't want to have to hand-code the TypeScript api-client every time I tweak the API in rust.

How should I approach this in Rust? Parse the rust-code and process the AST? Use a macro to generate code that can output the TypeScript api-client?

Denis Lisov
@tanriol
Jul 19 2018 23:36
I'd probably look at generating from an API description both the glue parts of the server code and the client code...
Talden
@Talden
Jul 19 2018 23:43
The client-builder needs to identify endpoint methods their HTTP methods, paths and parameterisation, and the structure of the types that will be serialised in and out of the methods. It's looking likely that I need to process the AST of the crate looking for endpoints - I see there's a mechanism of rustc producing a JSON AST - maybe that's the way I'll need to go.