Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    RuRu92
    @RuRu92
    Ah, so I was working with function pointer, as my closure was not capturing anything
    So how should i change my signature and implement closure to be Fn/FnMut ?
    tanriol
    @tanriol:matrix.org
    [m]
    What's your signature?
    Ah, I see it above. I think that changing action to action: impl FnOnce(con: &mut Transaction) -> Result<R> should work if you don't need object safety.
    @RuRu92: By the way, an off-topic question: do I understand correctly that Java closures do not support checked exceptions like SQLException? Learning some Java now, and after Rust it feels... strange.
    RuRu92
    @RuRu92

    @tanriol:matrix.org
    Thanks, I will try that out! Why would it not give me object safety? Curious to understand how to make good rust code.

    As for the Java.
    If its in the lambda, you have to explicitly handle checked exceptions using try-catch, and convert that to a runtime exception.
    It may seem strange, but its other way around for me. Done Java for so many years, other languages seem so foreign :D
    But I am enjoying Rust, want to master it!

    RuRu92
    @RuRu92

    @tanriol:matrix.org
    To make it looks nicer when handling exception throwing code, you can implement a throwing functional interface.

    something like

    @FunctionalInterface
    public interface ThrowingConsumer<T, E extends Exception> {
        void accept(T t) throws E;
    }

    And then you when you call that, it will look better

    tanriol
    @tanriol:matrix.org
    [m]
    Object safety does not allow type (or const) generics because Rust does not do automatic type erasure. There are ways around that, usually by splitting the trait into two - the object-safe "core" and the "extras" for better ergonomics.
    RuRu92
    @RuRu92
    So for my case. the unsafe part is that I have generic in the Result<R> ?
    How would handle this?
    tanriol
    @tanriol:matrix.org
    [m]
    First, if you don't need in_transaction to be a part of an object-safe trait, you don't need to do anything :-)
    RuRu92
    @RuRu92

    So you saying that this is fine way to do it?
    I assume this code isnt going to be problematic due to object unsafety?

    Want to have this as production viable code :)

    tanriol
    @tanriol:matrix.org
    [m]
    This is a fine way - it has some limitations, but these may not matter for your use case.
    RuRu92
    @RuRu92
    Perfect! I can then continue on expanding the code.
    Once I got something full fledged, you could take a look at the repo?
    I like feedback :D
    tanriol
    @tanriol:matrix.org
    [m]
    If I have enough time.
    MCF
    @mcf-rocks
    how to use generic constants?
    fn from_str<const N: usize>(s: &str, N: usize) -> Box<[u8; N]> {
        return Box::new([1;N]);
    }
    how?
    tanriol
    @tanriol:matrix.org
    [m]
    You don't need N: usize in function arguments.
    MCF
    @mcf-rocks
    amazing
    Félix Lescaudey de Maneville
    @ManevilleF

    Hello, question on the cargo manifest:

    Can I disable a feature when one is enabled? My lib can be asynchronous or blocking but not both at the same time.

    Is there any way to disable the async feature when blocking is enabled?

    default = ["async"]
    blocking = ["blocking", !"async"]
    tanriol
    @tanriol:matrix.org
    [m]
    Sorry, no way. Furthermore, if this is a library, note that your user can have multiple crates that depend on it, some with blocking, some with async
    So designing a library in such a way that can be either but not both is usually not a good idea.
    Félix Lescaudey de Maneville
    @ManevilleF
    thank you
    Standaa
    @Standaa
    Hi all ! Looking for advice regarding a piece of code I wrote. Is there a way to improve this or make it more Rusty 🙂 ?
             let mut module_path = if ts_config_exist {
                format!("{}/migrations/deploy.ts", cur_dir.display())
            } else {
                format!("{}/migrations/deploy.js", cur_dir.display())
            };
    
            if ts_config_exist {
                if let Err(_e) = std::process::Command::new("tsc")
                    .arg(&module_path)
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit())
                    .output()
                {
                    std::process::exit(1);
                }
                module_path = format!("{}/migrations/deploy.js", cur_dir.display())
            }
    Itanq
    @Itanq
    test
    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 :-)