rust - Allowing both static variables and boxes as a function argument? -


i have struct, instantiate statically, , i'd users allocate on heap. possible allow both in arguments function?

pub struct mydata {     x: i32 }  static allocated_statically: mydata = mydata {x: 1};  // should signature be? fn use_data(instance: box<mydata>) {     println!("{}", instance.x); }  fn main () {     use_data(box::new(mydata{x: 2}));     // doesn't work     use_data(allocated_statically); } 

in both instances, can pass pointer function.

pub struct mydata {     x: i32 }  static allocated_statically: mydata = mydata { x: 1 };  // should signature be? fn use_data(instance: &mydata) {     println!("{}", instance.x); }  fn main () {     use_data(&box::new(mydata{ x: 2 }));     use_data(&allocated_statically); } 

note in both cases, caller needs use & operator take address of value. in first call, operator yields &box<mydata>, compiler automatically converts &mydata because box implements deref trait.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -