These are chat archives for rust-lang/rust

12th
Nov 2018
David Lewis
@davidarmstronglewis
Nov 12 2018 01:58
Hey, does anyone know an efficient way to convert a Vec<Vec<T>> into a Vec<T>?
I was thinking I could drain in a loop, but I dunno
Alexandre Bury
@gyscos
Nov 12 2018 02:04
Flat map?
David Lewis
@davidarmstronglewis
Nov 12 2018 02:10
Okay, cool - I knew there was an iter method somewhere :). Thank you!
aohan237
@aohan237
Nov 12 2018 06:58
hello...wonder about ...why rust have to use trait..rather not to auto use these trait who use it...
Tim Robinson
@1tgr
Nov 12 2018 07:23
Two traits can have methods with the same name
aohan237
@aohan237
Nov 12 2018 07:24
why trait cant be like lifetime, mostly you wont write, when conflict or cant infered ,then you should write it down?
Tim Robinson
@1tgr
Nov 12 2018 07:26
You could upgrade one of your dependencies and they add a new method that conflicts… even if you’re not using it, it breaks your existing code
Same reason use some_crate::* is not the default
aohan237
@aohan237
Nov 12 2018 07:28
thanks….and Which is the best id for rust? My vscode and rust jet brain extension won’t give the right tips and navigation is sometimes not working properly
it is really painful when compare to other language
best ide for rust?
Tim Robinson
@1tgr
Nov 12 2018 07:46
I’m very happy with the JetBrains plugin
Yes I’m often finding cases in the code where it doesn’t work, but it does enough to be useful
aohan237
@aohan237
Nov 12 2018 08:14
so how to use self in a closure?
it has some lifetime issues
Use close?
Clone?
Tim Robinson
@1tgr
Nov 12 2018 08:21
It’s the same as any other variable, you can take it as a reference, move it or clone it, depending on the situation
With futures-based code I often find myself moving self into the first closure, then returning it from the closure so it can be moved into the second, and so on
However, it’s often easier to split self into multiple fields at the start, and reference just the fields you need from each closure
aohan237
@aohan237
Nov 12 2018 08:23
can you show me some sample code?
melbourne2991
@melbourne2991
Nov 12 2018 08:48
Maybe a dumb question but how can I read the first value of a vector.
I'm calling first() which returns a reference, which I can't deref because "cannot move out of borrowed content".
If I tried my_vec[0] I get an error saying it could be out of bounds, which makes sense...
@melbourne2991 you mean this?
melbourne2991
@melbourne2991
Nov 12 2018 09:00
mm my vector is borrowed
So I get "cannot move out of indexed content"
Also my vector is empty initially.
So that would be out of bounds
Denis Lisov
@tanriol
Nov 12 2018 09:03
@melbourne2991 What do you want to happen with your vector? Do you want to have a copy (the original value is still there) or to move it out (it's no longer in the vector)?
melbourne2991
@melbourne2991
Nov 12 2018 09:04
I want a copy
This is my struct
pub struct Parser {
  tree: ASTTree,
  token: Option<(TokenType, TokenMetadata)>,
  state: Vec<(NonTerminal, ASTNonTerminal)>,
}
and my method in Parser impl:
  fn current_state(&self) -> Option<&NonTerminal> {
    if let Some((non_terminal, _ast)) = self.state.first() {
      return Some(non_terminal);
    }

    None
  }
Currently returning the reference - but I want the value of first
A copy of it
Well I don't really care if it's a copy or not - I just need the value. But when I use references then it causes other borrowing issues in the caller of current_state.
Denis Lisov
@tanriol
Nov 12 2018 09:07
You mean of the NonTerminal stored there? Is the value big or small, does it contain boxes or something like that?
melbourne2991
@melbourne2991
Nov 12 2018 09:07
NonTerminal is just an enum so it's small - so a copy should be cheap?
Denis Lisov
@tanriol
Nov 12 2018 09:08
If it's just a enum without payloads, I'd mark it with #[derive(Clone, Copy)]
aohan237
@aohan237
Nov 12 2018 09:08
You really need a copy..
melbourne2991
@melbourne2991
Nov 12 2018 09:09
If I add derive .first() still gives me referenced values though
I did try adding #[derive(Clone, Copy)] previously
Just tried then to confirm - I still get &NonTerminal
aohan237
@aohan237
Nov 12 2018 09:11
so. you maybe need to_owned?
Denis Lisov
@tanriol
Nov 12 2018 09:12
And then you can
if let &Some((non_terminal, _)) = self.state.first() { ... }
melbourne2991
@melbourne2991
Nov 12 2018 09:12
    if let Some((non_terminal, _ast)) = self.state.first().to_owned() {
      return Some(non_terminal);
    }
Still giving me a reference ;(
Mm @tanriol
expected enum `std::option::Option`, found reference

note: expected type `std::option::Option<&(compiler::parser::NonTerminal, compiler::parser::ASTNonTerminal)>`
         found type `&_`
aohan237
@aohan237
Nov 12 2018 09:14
first give you a option?
You may need unwrap?
you compare option..
Why don’t use match
melbourne2991
@melbourne2991
Nov 12 2018 09:16
if let is effectively the same
just different syntax
I think
aohan237
@aohan237
Nov 12 2018 09:17
maybe. left some is some you owned ,but right is option(with ref)
Some(a) == Some(&a)
that’s the different..
@melbourne2991
maybe this?
Tim Robinson
@1tgr
Nov 12 2018 09:29
@aohan237 here’s an example of the second one, splitting self into fields and using the right field in the right closure https://medium.com/@GolDDranks/things-rust-doesnt-let-you-do-draft-f596a3c740a5#da48 ("Capturing only disjoint fields in closures
“)
aohan237
@aohan237
Nov 12 2018 09:30
@1tgr thanks ,i’ll go to learn it
Tim Robinson
@1tgr
Nov 12 2018 09:30
@aohan237 the first one is something like,
f.and_then(|x| {
    self.do_something(x);
    self
}).map(|self_| {
    self_.do_something_else();
})
Note you can’t name a variable self, you have to name it self_ or this or ...
Denis Lisov
@tanriol
Nov 12 2018 09:33
Sorry, thinko, & should have been inside Some
aohan237
@aohan237
Nov 12 2018 09:35
The first one ,if in future, if you do something with x, for example, x is an response.body, if you update self.name with x, this will have a lifetime issue? Right?
@1tgr
Tim Robinson
@1tgr
Nov 12 2018 09:36
It depends on the situation
aohan237
@aohan237
Nov 12 2018 09:36
there will be an error :"type must satisfy the static lifetime"
Tim Robinson
@1tgr
Nov 12 2018 09:36
If x is a reference, you won’t be able to use x outside of that closure
You can’t do this:
f.and_then(|x: &str| {
    self.name = x;
    self
})
aohan237
@aohan237
Nov 12 2018 09:39
but if it is an http response
so it should not have lift time issue. Right?
Do you use actix-web?
@1tgr
Tim Robinson
@1tgr
Nov 12 2018 09:40
No, I haven’t used it
aohan237
@aohan237
Nov 12 2018 09:40
Ok…i will check it myself..
Akos Vandra
@axos88
Nov 12 2018 09:47

Hi,

I recently upgraded from 1.28 to 1.30, and OUT_DIR seems to have stopped being defined:

src/routes/statics.rs:

  include!(concat!(env!("OUT_DIR"), "/data.rs"));
error: couldn't read "src/routes/false/data.rs": No such file or directory (os error 2)
  --> src/routes/statics.rs:11:1
   |
11 | include!(concat!(env!("OUT_DIR"), "/data.rs"));
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

any idea why?
the file is being generated and updated

$ find . -name data.rs
./target/arm-unknown-linux-gnueabihf/debug/build/rust-angular-5121d155d2df7f5/out/data.rs
./target/debug/build/rust-angular-66683cf9bc17b7b/out/data.rs
./target/debug/build/rust-angular-2faa36bb832fed9/out/data.rs

one of those was updated during the last few builds

Tim Robinson
@1tgr
Nov 12 2018 09:49
Hi @axos88 I saw your message yesterday, I haven’t seen any problem in 1.30
I have a few build scripts successfully using OUT_DIR
melbourne2991
@melbourne2991
Nov 12 2018 10:22
@tanriol that worked! Fantastic thank you
Akos Vandra
@axos88
Nov 12 2018 10:34
@1tgr thanks I will take another look then. But note that I am trying to use OUT_DIR not only from the build script (it's defined there), but from a "normal" source file to include the generated source.
Tim Robinson
@1tgr
Nov 12 2018 10:34
Yep, same here
Akos Vandra
@axos88
Nov 12 2018 10:34
And it seems to not be defined there
Ah ok ty
Weird
Tim Robinson
@1tgr
Nov 12 2018 10:36
OUT_DIR must be set to something, otherwise the code would try to include a file called ”/data.rs”, in the root directory
melbourne2991
@melbourne2991
Nov 12 2018 10:48
Can anyone tell me how you give enums that take a value (not sure what the proper terminology is) a copy trait via macros?
Eg: str, name and symbol below....
#[derive(Debug, Copy)]
pub enum TokenType {
  LeftParen,
  RightParen,
  Str(String),
  Name(String),
  Symbol(String),
}
Tim Robinson
@1tgr
Nov 12 2018 10:48
You can’t because String is not Copy
You can do Clone though
#[derive(Debug, Clone)]
pub enum TokenType {
  LeftParen,
  RightParen,
  Str(String),
  Name(String),
  Symbol(String),
}
melbourne2991
@melbourne2991
Nov 12 2018 10:49
Oh ok
Cool, thanks
This channel has really been a lifesaver. :thumbsup:
uncotion
@uncotion
Nov 12 2018 10:59
I don’t know what’s <S=()> in this code.
pub struct Abbas<S = ()> { /* fields omitted */ }
Could tell me what is name of this concept ?
Tim Robinson
@1tgr
Nov 12 2018 11:00
() is the name of a type, you would say its name “unit"
Abbas has a type parameter called S, and S defaults to the unit type (), although you can override S
let a: Abbas = //…
let b: Abbas<()> = //… 
let c: Abbas<i32> = //…
uncotion
@uncotion
Nov 12 2018 11:01
aha , so many thanks. so it’s somting like of templates in cpp.
🙏🙏
Tim Robinson
@1tgr
Nov 12 2018 11:02
In Rust, the stuff inside < … > looks similar to, and is used for similar things as, templates in C++
uncotion
@uncotion
Nov 12 2018 11:03
@1tgr : So many thanks for sharing refrence 🙏🙏💐💐.
aohan237
@aohan237
Nov 12 2018 11:20
I have an about ..if you generate a string in a fn ,but you reassign it to a strict member,what's the life time of the string?will it has lifetime issue?
adout
question..
Denis Lisov
@tanriol
Nov 12 2018 11:20
If you store a String (so your structure owns it), there's no lifetime issues.
Akos Vandra
@axos88
Nov 12 2018 11:21
@1tgr What do you mean OUT_DIR has to be set to something? It should be defined automatically by cargo shouldn't it? That's what happens in the build script.
Tim Robinson
@1tgr
Nov 12 2018 11:21
Yeah, I mean it can’t be truly missing in your case
aohan237
@aohan237
Nov 12 2018 11:21
client::ClientRequest::get(url.as_str())
    .finish()
    .unwrap()
    .send()
    .map_err(Error::from)
    .and_then(|resp| {
        resp.body() // <- this is MessageBody type, resolves to complete body
            .from_err() // <- convert PayloadError to an Error
            .and_then(|body| {
                // <- we got complete body, now send as server response

                let token: AccessToken = serde_json::from_slice(&body).unwrap();
                self.token.access_token = "ssss";
                Ok(HttpResponse::Ok().body(body))
            })
    }).responder()
so why this code has an lifetime issue..
confused a lot
Tim Robinson
@1tgr
Nov 12 2018 11:22
Can you annotate it with explicit types?
.and_then(|resp: ???| {
.and_then(|body: ???| {
What is ??? in each case?
aohan237
@aohan237
Nov 12 2018 11:23
this is the actix_web httpresponse
Akos Vandra
@axos88
Nov 12 2018 11:23
the problem is self
you need to turn it into an actor future
aohan237
@aohan237
Nov 12 2018 11:23
you can think of hyper request or response too
Akos Vandra
@axos88
Nov 12 2018 11:23
and then you will get a &mut this: Actor,
and use that instead of self
the problem is self may go away by the time the future gets executed
aohan237
@aohan237
Nov 12 2018 11:24
so I have to implement actor for my struct?
Akos Vandra
@axos88
Nov 12 2018 11:25
what is self here?
aohan237
@aohan237
Nov 12 2018 11:25
struct service {token :Token}
like this
Akos Vandra
@axos88
Nov 12 2018 11:26
i'm not sure what the solution is in this case - i had this issue with actors, so it was a bit easier to fix
however can you take a look what happens if you remove the self.access_token = ... line?
does it compile?
aohan237
@aohan237
Nov 12 2018 11:28
if remove everything works fine
I have done that
so what's your solution?
can you show me some sample code
Akos Vandra
@axos88
Nov 12 2018 11:31
yeah
one moment
aohan237
@aohan237
Nov 12 2018 11:31
thanks
Akos Vandra
@axos88
Nov 12 2018 11:32
trying to find a less confusing one
aohan237
@aohan237
Nov 12 2018 11:32
en..
Akos Vandra
@axos88
Nov 12 2018 11:33
this is some ugly shit, but it should give you an idea
impl Handler<AuthorizeCard> for CardAuthorizer {
    type Result = Box<ActorFuture<Item = (), Error = (), Actor = Self>>;

    fn handle(&mut self, msg: AuthorizeCard, ctx: &mut Self::Context) -> Self::Result {
        let reader_id = msg.0;
        let card_id = msg.1.id;

        let path: Vec<String> = vec!["card_readers", reader_id.as_str(), "authorizedCards"].into_iter().map(String::from).collect();
        let msg = actors::config::input::Read::<AuthorizedCardsConfig, _>::new(path.into_iter());

        let f = self.config_addr.send(msg).into_actor(self);

        let f = f.map( move |authorized_cards, this, ctx| {
            let authorized_cards: AuthorizedCardsConfig = authorized_cards.unwrap();
            let entries = authorized_cards.get(&card_id.to_string());

            match entries {
                Some(entries) => {
                    info!("Card Authorized {:#X} for {:?}!", card_id, entries);

                    entries.iter().for_each( |lock_id| {
                        match this.locks.get(lock_id) {
                            Some(lock_addr) => lock_addr.do_send(actors::lock::Input::Open(None)),
                            None => error!("Lock with ID {:?} not found!", lock_id)
                        }
                    });
                },
                None => info!("Card Unauthorized {:#X}!", card_id)
            }
        }).map_err(|e, this, ctx| ());

        Box::new(f)
    }
}
you can see that I have called into_actor on the future, and then I get a reference to Self via "this"
i'm not sure it will apply to your case though
but yeah, your problem indeed is that self may or may not exist by the time the http response comes back, the compiler can't make sure you won't reference memory that has been freed
btw, because of this, usually when passing in variables to a future transformation closure, you need to use move
aohan237
@aohan237
Nov 12 2018 11:38
yeah……thanks..it seems that mainly is the actor issue
Akos Vandra
@axos88
Nov 12 2018 11:39
sorry i couldn't help more, I'm not super-experienced when it comes to rust
btw, there is an actix/actix channel, the guys there are super-helpful, and may be able to help you out better
aohan237
@aohan237
Nov 12 2018 11:41
helps a lot ..I have asked in actix_web ,until now no answers
melbourne2991
@melbourne2991
Nov 12 2018 11:52
Guys, I have a Vector that will hold a bunch of things, I would then like to hold references to those things in other vectors. Does this call for the use of something like Box?
Tim Robinson
@1tgr
Nov 12 2018 11:54
No, if you put something in a Vec, you can hold a reference to it
You won’t be able to modify the Vec as long as you have a reference to a thing within it though
This is talking about plain references, &
melbourne2991
@melbourne2991
Nov 12 2018 11:54
Yep because that would invalidate the reference right?
Tim Robinson
@1tgr
Nov 12 2018 11:54
Shared ownership via Arc or Rc is more flexible
Right
As soon as you give somebody a & reference inside the Vec, you can’t make a new &mut reference to the Vec
melbourne2991
@melbourne2991
Nov 12 2018 11:57
My scenario is I'm trying to build a tree structure. I have a bunch of nodes which each have children. I would like all of those nodes stored in a single vector, but nodes need references to one another in their own children vector
Denis Lisov
@tanriol
Nov 12 2018 11:58
Why do you want all nodes to be stored in a single vector? Are you going to modify the tree after it's built?
melbourne2991
@melbourne2991
Nov 12 2018 11:59
Mm ok, so I could possibly do without that
but I would still need references to them in the state vector
Is there something obviously wrong i'm doing here:
  fn new_parser_state(&mut self, non_terminal: ASTNonTerminal) {
    self.tree.nodes.push(non_terminal);
    self.state.push(&non_terminal);
  }
I get `non_terminal does not live long enough` I think I sort of understand why
but i'm not certain...
Tim Robinson
@1tgr
Nov 12 2018 12:03
I’d suggest getting this working using Rc<ASTNonTerminal>, and doing it in terms of references later if you need to
Denis Lisov
@tanriol
Nov 12 2018 12:03
A structure cannot both own some data and keep a reference to it at the moment. There are some suggestions about self-referential structures, but no consensus yet.
melbourne2991
@melbourne2991
Nov 12 2018 12:04
Ok so if I understand correctly, the above doesn't work because &non_terminal just refers to non_terminal by itself which doesn't point to it's position in the vector. &non_terminal is just a reference to non_terminal in the current scope?
Tim Robinson
@1tgr
Nov 12 2018 12:21
The Rust docs and tutorials are full of examples of references and borrowing, but that’s not all there is
You don’t have to use references on everything
melbourne2991
@melbourne2991
Nov 12 2018 12:22
If it's a large structure though, you don't want to copy it around
Oh I see, you mean "pure" references
In my mind Rc is a kind of reference - though not in the strictest meaning of the term
Tim Robinson
@1tgr
Nov 12 2018 12:25
Yeah true, I would call it a smart pointer, as “reference” in Rust is a specific thing
Underneath, Rc looks very similar to Box, and no memory is copied when the Rc moves from one place to another
melbourne2991
@melbourne2991
Nov 12 2018 12:29
Right ok, yeah just trying to understand when you would use one over the other
Akos Vandra
@axos88
Nov 12 2018 13:35
@aohan237 i can't see your message in actix/actix
aohan237
@aohan237
Nov 12 2018 15:29
i post it in actin/actix_web
@axos88
actix/actix_web
Akos Vandra
@axos88
Nov 12 2018 17:17
@aohan237 ah, i'm not up there, i'm only on actix/actix. it has a lot of actix_web traffic too
tandrysyawaludin
@tandrysyawaludin
Nov 12 2018 18:23
I try to install diesel_cli on heroku to use diesel migration run later but i got this error. Does anyone know why is this happen?
Screen Shot 2018-11-13 at 01.25.28.png
Screen Shot 2018-11-13 at 01.25.44.png
Ichoran
@Ichoran
Nov 12 2018 18:31
Seems pretty clear at the end that it can't find the sqlite3 library. Do you have it installed?
tandrysyawaludin
@tandrysyawaludin
Nov 12 2018 18:34
how to install sqlite3 on heroku?
Ichoran
@Ichoran
Nov 12 2018 19:19
I don't know. Maybe someone here does, but it's not a Rust-specific question.
Yemi Bedu @ P&R
@pr-yemibedu
Nov 12 2018 22:00
and what you would be looking for is the sqlite3-devel library to be installed.