These are chat archives for rust-lang/rust

28th
Nov 2018
amitayadav
@amitayadav
Nov 28 2018 06:40
please provide me solution of following error:no function or associated item named from_cdrs_r found for type uuid::Uuid in the current scope
as well error2: "the trait bound cdrs::types::value::Bytes: std::convert::From<uuid::Uuid> is not satisfied"
aohan237
@aohan237
Nov 28 2018 07:19
hi i have an question about 'static lifetime
the static lifetime means life will live until the program stops... if i started huge static str, this will consume lots of memory or even panic?
huge number of 'static str
even i dont use them
if so ,why futures requires static, which will live until the whole program stops
Tim Robinson
@1tgr
Nov 28 2018 07:24
That's not what 'static means on futures
It means that the future can outlive the function that creates it, not that it will
aohan237
@aohan237
Nov 28 2018 07:25
yeah i know it
Tim Robinson
@1tgr
Nov 28 2018 07:25
It means "the future (and any and_then closures etc) don't contain any 'a references"
Sure, your future can use a 'static reference
aohan237
@aohan237
Nov 28 2018 07:25
but static life time still works? and the future will not destroy?
Tim Robinson
@1tgr
Nov 28 2018 07:26
Or it can use Rc or Arc, either of which can outlive the function that creates the future, but don't live as long as the entire program

but static life time still works? and the future will not destroy?

Not sure what you mean?

aohan237
@aohan237
Nov 28 2018 07:27
i mean , everything with 'static life time will live until the entire program stops
so , it confused about the object who uses the 'static lifetime
if not ,the 'static lifetime should change it definition in the rust-book
Tim Robinson
@1tgr
Nov 28 2018 07:29

everything with 'static life time will live until the entire program stops

No, that's not right

aohan237
@aohan237
Nov 28 2018 07:29
so how to understand 'static lifetime
Tim Robinson
@1tgr
Nov 28 2018 07:29
Something with a 'static lifetime could live until the program stops, if it wanted to
But it doesn't have to
aohan237
@aohan237
Nov 28 2018 07:29
so who decide to destroy the static lifetime?
Tim Robinson
@1tgr
Nov 28 2018 07:30
For instance, any object you own is 'static, provided it doesn't contain any references of its own
String is 'static
And you decide when to destroy a String
Heh, even i32 is 'static - you own an i32, and i32 doesn't refer to any other object
aohan237
@aohan237
Nov 28 2018 07:30
i didnt destroy manually,but compiler did
Tim Robinson
@1tgr
Nov 28 2018 07:31
Sure, the compiler destroyed it because your code decided it no longer needed it
aohan237
@aohan237
Nov 28 2018 07:32
so 'static should named as live long as until you dont need
but not the entire program
and means you dont care much more about its lifetime
Tim Robinson
@1tgr
Nov 28 2018 07:34
Exactly
aohan237
@aohan237
Nov 28 2018 07:34
One special lifetime we need to discuss is 'static, which denotes the entire duration of the program
"One special lifetime we need to discuss is 'static, which denotes the entire duration of the program"
octave99
@octave99
Nov 28 2018 07:35
Hello, Is there was to put endianness to get bytes from Struct like so
std::slice::from_raw_parts((my_struct as *const _) as *const u8, std::mem::size_of::<MyStruct>())
aohan237
@aohan237
Nov 28 2018 07:35
this sentence really confused me about how static runs
octave99
@octave99
Nov 28 2018 07:35
By defaults its spilling little endian, I am however in need for big endian
Tim Robinson
@1tgr
Nov 28 2018 08:27
@polygdev for both big and little endian, you should be writing the struct field by field
Don’t rely on the as *const _ technique as the compiler can rearrange fields, even beyond reordering and alignment - the Rust compiler optimises memory layout much more than a C or C++ compiler would
Take a look at the byteorder crate, which has helper functions for writing fields in little or big endian format
octave99
@octave99
Nov 28 2018 08:29
@1tgr Sure. I was trying bincode which is good. But it serialize enum to u32, even with #[repr(u16)] over enum, its still giving out u32
Could not yet figure out how to have bincode return u16 or u8 for an enum
Tim Robinson
@1tgr
Nov 28 2018 08:30
But serialise your_enum as u16?
@aohan237 that sentence is write about the lifetime of static objects, like string literals
octave99
@octave99
Nov 28 2018 08:31
yes
Tim Robinson
@1tgr
Nov 28 2018 08:31
But when you look at futures code you’re looking at a lifetime bound, where T: 'a
octave99
@octave99
Nov 28 2018 08:32
use bincode;

#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
#[repr(u16)]
pub enum MyEnum {
  First = 11,
  Unknown = 0,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
#[repr(packed)]
struct MyStruct {
  item: MyEnum,
}

#[cfg(test)]
mod tests {
  use super::{MyEnum, MyStruct};
  use bincode;
  #[test]
  fn decode_test() {
    let ms = MyStruct {
      item: MyEnum::First,
    };
    print!("{:?}", ms);
    let c = bincode::config().big_endian().serialize(&ms).unwrap();
    print!("\nBINCODE: {:?}\n", c);
  }
}
I expect output as [0, 11]
Tim Robinson
@1tgr
Nov 28 2018 08:32
That lifetime means either:
T contains has no references, so don’t worry about it, or
T contains references, and they live as long as 'a (or longer)
octave99
@octave99
Nov 28 2018 08:32
Not sure, why its returning [0,0,0,0]
Tim Robinson
@1tgr
Nov 28 2018 08:34
A T: 'static lifetime bound means that T contains no references (don’t worry about it!), or, if T contains references, they are references to something 'static like a string literal
@polygdev I’d need to read up on repr but to me that looks like Rust’s optimised enum layout
octave99
@octave99
Nov 28 2018 08:36
Do you recommend some other way and mean to achieve the result?
Tim Robinson
@1tgr
Nov 28 2018 08:36
What does #[repr(c)] on the struct give you?
octave99
@octave99
Nov 28 2018 08:37
Same [0,0,0,0]
Tim Robinson
@1tgr
Nov 28 2018 08:37
I’d always do this stuff by defining a separate binary format and writing the fields one by one
octave99
@octave99
Nov 28 2018 08:37
What I am doing currently is to have decoding struct written with enums for readability during output
and another structure for encode with primitives
Tim Robinson
@1tgr
Nov 28 2018 08:38
Hm, how is bincode’s format defined?
I’d expect your struct implement some Serialize trait like in Serde
This message was deleted
Paul Masurel
@fulmicoton
Nov 28 2018 08:39
I don't know if serde cares about the memory representation of your enum
octave99
@octave99
Nov 28 2018 08:40
So, you mean, implement serde serializer for a struct and make it work the way I like?
Tim Robinson
@1tgr
Nov 28 2018 08:40
No, but the underlying binary format will
Serde’s job is just to automate the “write every field to a serializer” part
I haven’t tried Bincode but the https://serde.rs home page mentions it as the second bullet point
octave99
@octave99
Nov 28 2018 08:42
Infact, bincode uses serde as showed at the https://serde.rs under data format
Paul Masurel
@fulmicoton
Nov 28 2018 08:47
But yeah, implementing Serialize and Deserialize manually should do the trick.
octave99
@octave99
Nov 28 2018 08:47
@fulmicoton Thats what I feel like now
Infact byteorder also looks nice and works like golang's binary reader/writer, but not sure about performance when compared to serde
trsh
@trsh
Nov 28 2018 08:49
@Ichoran thanks for advice
Paul Masurel
@fulmicoton
Nov 28 2018 08:49
Something like this I suppose...
octave99
@octave99
Nov 28 2018 08:53
Thanks you. Let me try with that. I might have 50-60 enums going forward and doing it for every enum will be too much, thats why was looking for something like bincode.
Paul Masurel
@fulmicoton
Nov 28 2018 08:54
you can make a macro if you use a casting style.
octave99
@octave99
Nov 28 2018 08:54
yeah, thats a good idea in fact. Let me play around to see what works best
@fulmicoton It says casting MyEnum to u16 is invalid
Paul Masurel
@fulmicoton
Nov 28 2018 08:59
ah?
octave99
@octave99
Nov 28 2018 08:59
does it require to be casted through the pointer
as the error says
In here, serializer.serialize_u16(self as u16)
self is a reference
*self as u16
the other cast is problematic however
octave99
@octave99
Nov 28 2018 09:01
Yeah that worked perfectly
Paul Masurel
@fulmicoton
Nov 28 2018 09:01
extern crate num_traits;

use num_traits::FromPrimitive;

#[derive(FromPrimitive)]
enum MyEnum {
//...
}
octave99
@octave99
Nov 28 2018 09:04
@fulmicoton Thanks.
octave99
@octave99
Nov 28 2018 09:16
So what has finally worked is, let the bincode handle the struct serialization for primitives and implement serializer for enums. Thanks @fulmicoton and @1tgr
trsh
@trsh
Nov 28 2018 10:54
Love rust 1.3x
With building progress bar
Also it seems faster in compiling
Tim Robinson
@1tgr
Nov 28 2018 11:55
Yes!
I don't understand how I've been coding for this long without having a progress bar in my compiler
laurent bernabé
@loloof64
Nov 28 2018 17:10
Hi everyone : a trivial one maybe.
How can I get rid of error "Cannot move out of borrowed content" in the following ?
pub fn get_piece_image_from_piece(&self, piece: Piece) -> Pixbuf {
        match piece.role {
            Role::Pawn => {
                if piece.color.is_white() 
                {
                    self.white_pawn
                }
                else
                {
                    self.black_pawn
                }
            },
            Role::Knight => {
                if piece.color.is_white() 
                {
                    self.white_knight
                }
                else
                {
                    self.black_knight
                }
            },
            Role::Bishop => {
                if piece.color.is_white() 
                {
                    self.white_bishop
                }
                else
                {
                    self.black_bishop
                }
            },
            Role::Rook => {
                if piece.color.is_white() 
                {
                    self.white_rook
                }
                else
                {
                    self.black_rook
                }
            },
            Role::Queen => {
                if piece.color.is_white() 
                {
                    self.white_queen
                }
                else
                {
                    self.black_queen
                }
            },
            Role::King => {
                if piece.color.is_white() 
                {
                    self.white_king
                }
                else
                {
                    self.black_king
                }
            },
        }
    }
(self.white_pawn, self.black_king,... => the errorneous lines)
#[derive(Clone)]
pub struct PieceImages
{
    pub white_pawn: Pixbuf,
    pub white_knight: Pixbuf,
    pub white_bishop: Pixbuf,
    pub white_rook: Pixbuf,
    pub white_queen: Pixbuf,
    pub white_king: Pixbuf,

    pub black_pawn: Pixbuf,
    pub black_knight: Pixbuf,
    pub black_bishop: Pixbuf,
    pub black_rook: Pixbuf,
    pub black_queen: Pixbuf,
    pub black_king: Pixbuf,
}
The method above belongs to impl PiecesImages
octave99
@octave99
Nov 28 2018 17:36
@loloof64 What is Pixbuf?
Lyle Mantooth
@IslandUsurper
Nov 28 2018 17:45
@loloof64, use self.black_pawn.clone(), etc. or change your returnt type to &Pixbuf and use &self.black_pawn, etc.
Which you need depends on how you use the returned value, and how big a Pixbuf is.
Sylwester Rąpała
@xoac
Nov 28 2018 18:01
I have a Vec<MegableItems> I would like to iterate mutable over this items and call item1.merge(item2). In next iteration item2.merge(item3) and so on..
MergableItems has fn merge(&mut self, other: &mut MergableItems). Is this easily possible with safe rust?
Lyle Mantooth
@IslandUsurper
Nov 28 2018 18:07
Should be easy. But use into_iter() on the Vec so that the items get moved out.
Or maybe iter_mut, if you have to keep them around. But start with an "empty" item, not the first one int heVec.
Sylwester Rąpała
@xoac
Nov 28 2018 18:08
@IslandUsurper
let mergable_items : Vec<MergableItem> = vec![item1, item2, item3];

for (item1, item2) in mergable_items.?? {
  item1.merge(item2)
}
Lyle Mantooth
@IslandUsurper
Nov 28 2018 18:09
So, is item1 staying in mergable_items? Is item2?
Sylwester Rąpała
@xoac
Nov 28 2018 18:10
I have updated example to be more clear where are items
The problem is I want to iterate not with one element but wiith 2 at once
Lyle Mantooth
@IslandUsurper
Nov 28 2018 18:12
I think either Vec or Iterator has a windows() function that will do that. Or maybe chunks(). But I'm still concerned about what result you actually want.
Like, should all things be merged together? Or is each even-numbered item merged to the odd ones? Does that mean your list is half as big now?
Or are you merging each one with it's neighbor, down the line?
That last one being equivalent to
item1.merge(&mut item2);
item2.merge(&mut item3);
Sylwester Rąpała
@xoac
Nov 28 2018 18:14
this iteration will be in loop and will go until at least one merge function succeed
Lyle Mantooth
@IslandUsurper
Nov 28 2018 18:15
Oh, merging might not even work? That changes things.
Sylwester Rąpała
@xoac
Nov 28 2018 18:15
to merge I use this fn merge(&mut self, other: &mut MergableItem) -> bool
Lyle Mantooth
@IslandUsurper
Nov 28 2018 18:24
having other be &mut causes problems.
Maybe. Try for (mut item1, mut item2) in mergable_items.windows(2) {}
@xoac :point_up:
And the body of the loop would be if item.merge(&mut item2) { break; }
Well, "until at least" doesn't make a lot of sense. You can either do "until it succeeds", or you hope "at least one merge function succeeds"
Sylwester Rąpała
@xoac
Nov 28 2018 18:46
It will not work -- Windows<T> is still iterator
Lyle Mantooth
@IslandUsurper
Nov 28 2018 18:53
You have to use an iterator of some kind to use for.
I'm also still not sure you really want to do things this way to solve your problem.
laurent bernabé
@loloof64
Nov 28 2018 20:06
@IslandUsurper Thank you very much :smile:
Trying your suggestion right now
@polygdev Pixbuf is a class for managing Image in GtkRs
(Rust Gtk 3)
Michael Thomas
@Michaelt293
Nov 28 2018 21:00
I'm trying to write a macro but I'm running into some difficulties. Is it possible to use a function defined within the same module as the macro within the body of the macro? If so, is there any special syntax that is required?
Lyle Mantooth
@IslandUsurper
Nov 28 2018 21:09
Doesn't matter if the function is in the same module as the macro. The function has to be visible from wherever the macro is called, and you have to call it from within the macro as $crate::foo::function().
Michael Thomas
@Michaelt293
Nov 28 2018 21:15
Awesome, thanks for that. It's working now.
Lyle Mantooth
@IslandUsurper
Nov 28 2018 21:19
At first, I had read your question as "how do I define a function in a macro and use it within the macro", and I'm like, "Uh, that's not going to work." :D
Denis Lisov
@tanriol
Nov 28 2018 21:30
@loloof64 How about keeping the pixbufs in a HashMap<Piece, Pixbuf> or something like that? Your code looks like a lot of repetition at the moment :-(
laurent bernabé
@loloof64
Nov 28 2018 22:03
Thanks @tanriol I'll try this rather :smile:
Josh
@joshlemer
Nov 28 2018 22:12
Is it impossible to make a trait object for a Trait, which has a method with a type parameter?

for example

    trait Foo {
        fn a<T>(&self, t: T) -> T;
    }

    let foo: Box<dyn Foo> = unimplemented!();

it gives me

the trait `main::Foo` cannot be made into an object
  --> src/main.rs:26:14
   |
26 |     let foo: Box<dyn Foo> = unimplemented!();
   |              ^^^^^^^^^^^^ the trait `main::Foo` cannot be made into an object
   |
   = note: method `a` has generic type parameters

maybe that note means that no generic methods are allowed on trait objects?

Tim Robinson
@1tgr
Nov 28 2018 22:17
It does
On a trait object, all methods are baked into a virtual method table in advance
On your a, fresh code is generated by the compiler for every T that is used
If this method was part of a trait object then the compiler would have to generate code at runtime according to the concrete T type
Josh
@joshlemer
Nov 28 2018 22:29
ah k so the closest one could really get to this, is by having the argument also itself be trait object
    trait Foo {
        fn a(&self, t: Box<dyn Bar>) -> Box<dyn Bar>;
    }

    trait Bar {}

    let foo: Box<dyn Foo> = unimplemented!();
Tim Robinson
@1tgr
Nov 28 2018 22:32
Yeah, if your original method was a<T: Bar>(T) then a(Box<dyn Bar>) could be a usable approximation
And I haven’t tried this, but I think you can have a mix of object-safe and nonsafe methods on your trait, and the nonsafe ones don’t cause an error but are inaccessible via the trait object
laurent bernabé
@loloof64
Nov 28 2018 23:31
Thanks @tanriol It worked :smile: