Get data in mod file

How to get data in mod file from main?

mod mod_01 {

    pub fn test() {
         // println!("{:?}", ar1.len());
         // println!("{:?}", ar2[1]);
    }
}


fn main() {

   let mut ar1: Vec<i32> = vec![1, 2];
   ar1.push(3);
   
   let mut ar2: Vec<String> = vec!["abc".to_string(), "xyz".to_string()];
   ar2.push("qwe".to_string());
   
   
   println!("{:?}", ar1);
   println!("{:?}", ar2);
   mod_01::test();
}

play.rust-lang.org

You should probably pass the vector as an argument to the function. The concept of functions taking argents is pretty basic – please read an introductory tutorial and/or the relevant part of the Book instead of asking here.

Is it possible without using a function argument? Thanks.

Why don't you want to use a function argument?

I'm sure it's possible, but you shouldn't do that.

Is it good if there are a lot of arguments and speed is important.

If there are a lot of args, you could consider a configuration struct to pass as a single argument.

The alternative is to use a global variable, but that is almost certainly not what you want, and I would highly recommend avoiding doing that. It often causes more problems that it solves.

The speed difference for passing this as an argument is almost always going to be practically non-existent.

1 Like

What speed? Do you think that passing arguments is what slows your code down? Because that's not true.

1 Like

and I would highly recommend avoiding doing that
thanks.

I do not argue. thought that many arguments are already bad practice and architecture error. Speed is also important.

Many arguments is bad practice. Two is generally not. And if the number grows, you can combine them into a single struct.

Even then, many arguments is better practice than globals.

7 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.