Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Itanq
    @Itanq
    why rust not impl Default trait for any size array
    but impl Debug/Clone/Eq trait for any size array
    what is the difference between them
    tanriol
    @tanriol:matrix.org
    [m]
    @Itanq: Yes, this is an unfortunate difference. The problem is that an implementation of Default for [T; N] of any size would require T: Default and thus would conflict with existing impl<T> Default for [T; 0] that does not require that ("because it does not need to create any T").
    MCF
    @mcf-rocks
    what is type is rust enum implemented as?
    tanriol
    @tanriol:matrix.org
    [m]
    Do you mean the default type used for enum discriminant? Not sure, probably the smallest integer that's enough for it. Configurable with annotations like #[repr(u16)]
    MCF
    @mcf-rocks
    thx
    Félix Lescaudey de Maneville
    @ManevilleF

    Hello,

    If I want a structure like this:

    pub struct Manager {
           items: Vec<Item>,
           lists: Vec<ItemList>
    }

    Which holds a data vector of items and some item lists like this:

    pub struct ItemList {
           items: Vec<Item>
    }

    How can I make the items of ItemList to be references of the Manager::items ?
    I'm trying stuff with Rc and RefCell but I'm getting lost.

    I want the ItemList object to have mutability access to its listed items.

    Félix Lescaudey de Maneville
    @ManevilleF
    I got it to work with this:
    #[derive(Debug)]
    pub struct ItemList {
        items: Vec<Rc<RefCell<Item>>>
    }
    
    #[derive(Debug)]
    pub struct Manager {
        items: Vec<Rc<RefCell<Item>>>,
        lists: Vec<ItemList>,
    }
    juliusjh
    @juliusjh
    Why not use indices referring to the vector in Manager and avoid the Rc/RefCell stuff?
    1 reply
    nicraMarcin
    @nicraMarcin

    Hi, I'm new with Rust. I'm trying to use config crate with default values which are hardcoded and can be overwritten by config file.
    I can't set default empty vector in modules: Vec<Module>

    #[derive(Debug, Deserialize)]
    struct Module {
        name: String,
        // enabled: bool,
        // address: String,
        port: u16
    }
    
    #[derive(Debug, Deserialize)]
    pub struct Settings {
        database: Database,
        server: Server,
        modules: Vec<Module>
    }
    
    // In main()
    
            s.set_default("server.port", "8080")?;
            s.set_default("modules", "");
    
            s.merge(File::with_name("config/gurita"))?

    with this I have ConfigError about setting modules:

    invalid type: string "", expected a sequence

    If I set this in config file modules = [] that works, but I need to set as default in code and not to set empty vec in configuration file.
    How to write empty sequece in set_default() function?

    Félix Lescaudey de Maneville
    @ManevilleF

    Hello I have the following code:

    pub fn assume_node_at(&mut self, index: &Index) -> Result<&H3Node, H3LibError> {
            match self.get_node_at(index) { // mutable borrow
                Some(node) => Ok(node),
                None => {
                    self.incr_nb_nodes_added(); // mutable borrow
                    let res = self.add_index(index.clone())?; // mutable borrow
                    Ok(res)
                }
            }
        }

    Which doesn't compile:

    error[E0499]: cannot borrow `*self` as mutable more than once at a time
      --> h3lib/src/h3_tree.rs:53:17
       |
    49 |     pub fn assume_node_at(&mut self, index: &Index) -> Result<&H3Node, H3LibError> {
       |                           - let's call the lifetime of this reference `'1`
    50 |         match self.get_node_at(index) { // mutable borrow
       |               ---- first mutable borrow occurs here
    51 |             Some(node) => Ok(node),
       |                           -------- returning this value requires that `*self` is borrowed for `'1`
    52 |             None => {
    53 |                 self.incr_nb_nodes_added(); // mutable borrow
       |                 ^^^^ second mutable borrow occurs here
    
    error[E0499]: cannot borrow `*self` as mutable more than once at a time
      --> h3lib/src/h3_tree.rs:54:27
       |
    49 |     pub fn assume_node_at(&mut self, index: &Index) -> Result<&H3Node, H3LibError> {
       |                           - let's call the lifetime of this reference `'1`
    50 |         match self.get_node_at(index) { // mutable borrow
       |               ---- first mutable borrow occurs here
    51 |             Some(node) => Ok(node),
       |                           -------- returning this value requires that `*self` is borrowed for `'1`
    ...
    54 |                 let res = self.add_index(index.clone())?; // mutable borrow
       |                           ^^^^ second mutable borrow occurs here
    `

    I know where the problem is coming from but I don't know how to fix this. using lexical scopes, using if let, etc.
    Any idea?

    3 replies
    tanriol
    @tanriol:matrix.org
    [m]
    @nicraMarcin: You probably wanted s.set_default("modules", vec![]);
    6 replies
    tanriol
    @tanriol:matrix.org
    [m]
    @ManevilleF: This will likely "just work" in some later versions, but I'm not sure of the "proper" way of fixing this now.
    2 replies
    Félix Lescaudey de Maneville
    @ManevilleF

    Hello,

    I'm using a Arc<RwLock<T>> and my program seems to wait when I'm using .write() but it's the first to be called

    Any way I can debug this?
    tanriol
    @tanriol:matrix.org
    [m]
    @ManevilleF: By "seems to wait" do you mean hangs forever or something different?
    3 replies
    Kelly Thomas Kline
    @kellytk
    I'm working on a command-line tool for *nix. What's available to us to resolve a path pattern argument to an absolute path in a native Rust type? Take for example the rm command, and the path pattern argument it can be given. Some (non-exhaustive) examples are ., ~, ../foo, ./bar/. While I only care to support *BSD and Linux, portability to fringe OSs like Windows and macOS would be nice if free
    tanriol
    @tanriol:matrix.org
    [m]
    @kellytk: For . and .. Path::canonicalize should be enough, for ~ and ~username you may want to use a crate or implement that yourself.
    Kelly Thomas Kline
    @kellytk
    Thank you. Do you know of a crate I should look at for that @tanriol:matrix.org?
    tanriol
    @tanriol:matrix.org
    [m]
    For example, expanduser may work.
    Kelly Thomas Kline
    @kellytk
    Thanks a lot @tanriol:matrix.org, good to see you again BTW :-)
    slby
    @slby:matrix.org
    [m]
    Is it possible to automatically see if a derive macro is unused and can be removed?
    tanriol
    @tanriol:matrix.org
    [m]
    I don't know any easy way. Also, this channel is not often used, your chances in #rust:matrix.org are much higher :-)
    Lk
    @Lk2v
    hey
    slby
    @slby:matrix.org
    [m]
    tanriol: Thank you! Yeah, I tried there already! But sadly also no luck. :D
    Félix Lescaudey de Maneville
    @ManevilleF
    Hello, how can I initialize an array slice [u32; 122] with 122 0 values? I know how to it with a Vec<> but I can't manage to use the slice:
    #[derive(Debug)]
    pub struct Array {
        pub elements: [u32; 122],
    }
    
    fn main() {
        let vec :Vec<u32> = (0..122).map(|i| 0).collect();
        let arr = Array {
            elements: vec.as_slice()
        };
        println!("{:?}", arr);
    }
    Fixed it with: <[u32; 122]>::try_from(vec).unwrap()
    tanriol
    @tanriol:matrix.org
    [m]
    [0; 122]?
    1 reply
    tanriol
    @tanriol:matrix.org
    [m]
    When it goes out of scope or is destroyed explicitly.
    tanriol
    @tanriol:matrix.org
    [m]
    Well, you've specifically asked about an u32 array :-)
    Félix Lescaudey de Maneville
    @ManevilleF

    Hello,

    Is there any way to have a struct owning a type T and other structs referencing it in readonly with something like Arc<> or Rc<T>, it seems it's either shared ownership or no reference counting

    Félix Lescaudey de Maneville
    @ManevilleF

    Hello, I'm fighting with the borrow checker and I can't seem to win:

        pub fn find_child_mut(&mut self, index: &Index) -> &mut Self {
            let direction: u8 = index.direction();
            if let Some(child) = self.child_mut(&direction) {
                return child.find_child_mut(index)
            }
            self
        }

    The borrow checker thinks self might still be borrowed after my if let and return statement:

    171 |     pub fn find_child_mut(&mut self, index: &Index) -> &mut Self {
        |                           - let's call the lifetime of this reference `'1`
    ...
    176 |         if let Some(child) = self.child_mut(&direction) {
        |                              ---- first mutable borrow occurs here
    177 |             return child.find_child_mut(index)
        |                    --------------------------- returning this value requires that `*self` is borrowed for `'1`
    178 |         }
    179 |         self
        |         ^^^^ second mutable borrow occurs here

    I know the borrow checker is not smart but is there any way to fix this? I can't find a solution

    tanriol
    @tanriol:matrix.org
    [m]
    I'm afraid you need to check-and-unwrap instead of if let
    1 reply
    I think you need two child_mut calls - one for check, one for return :-(
    1 reply
    This is supposed to be fixed when the Polonius borrow checker becomes the default, but I'm not sure of its current status.
    Félix Lescaudey de Maneville
    @ManevilleF
    Yeah it's sad to have this kind of issues, I never heard of Polonius borrow checker, is it posible to enable it?
    tanriol
    @tanriol:matrix.org
    [m]
    On Nightly only, -Z polonius I think
    Félix Lescaudey de Maneville
    @ManevilleF
    Thank you for your help !
    RuRu92
    @RuRu92

    Got stuck in learning how to use mutexes..

    56 |         domain_settings.into_inner().expect("ERROR").get_password_reset_token_duration()
       |         ^^^^^^^^^^^^^ move occurs because `**domain_settings` has type `Mutex<InternalDomainSettings>`, which does not implement the `Copy` trait

    I got this struct

    pub struct DomainSettingProvider {
        settings: Arc<HashMap<DomainName, Mutex<InternalDomainSettings>>>,
        db: Arc<DB>,
    }

    The aim is to use this as a single point of entry for getting the settings. So acting like a cache, and having 1 thread that will update the map every so often.

    So far, it seems that getting values of the mutex pose to be a pain

    RuRu92
    @RuRu92

    This is the func that throws the error

     pub fn get_password_reset_token_duration(&self, domain: DomainName) -> Duration {
            let domain_settings = self.settings.get(domain).expect("Failed to get domain settings");
            domain_settings.into_inner().expect("ERROR").get_password_reset_token_duration()
        }

    Is this the right way to get values out of mutex in a hashmap?

    yorodm
    @yorodm:efym.net
    [m]
    Hi: I would go with Arc<Mutex<HashMap<DomainName,InternalDomainSettings>>> instead
    Or use RwLock if you're worried about reader threads starving
    yorodm
    @yorodm:efym.net
    [m]
    Also I think you want to avoid using into_inner unless you're discarding the Mutex, calling lock should be enough in your case
    RuRu92
    @RuRu92

    Hi @yorodm:efym.net
    Thanks for the answer.

    To understand better, its better to wrap the whole map into mutex ? Even though, the only value updated would the the settings?

    What does RwLock gives me? The data is going to be initialized on startup, I would assume that readers would be fine in this case.

    I will keep in mind regarding the into_inner.
    Does a lock on the mutex prevents readers from accessing the object?

    tanriol
    @tanriol:matrix.org
    [m]
    @RuRu92: If you don't need to add or remove domains, a per-entry lock would be fine.
    yorodm
    @yorodm:efym.net
    [m]
    Hi, I suggested to wrap the whole map in a Mutex or RwLock because of insert and remove operations, also it makes more sense to me not to keep a bunch of Mutexes (with HashMap<T, Mutex<K>> you're getting one for each entry in the map) but if you're not inserting or removing it would be fine
    tanriol
    @tanriol:matrix.org
    [m]
    And yes, you need lock, not into_inner
    RuRu92
    @RuRu92
    I think I follow now, that makes sense. And perhaps it is better to wrap the whole map.
    Besides that, I think I need RwLock as I need readers to not be blocked while having high volume of requests