Reputation: 1009
I'm trying to convert this simple C code to Rust:
#include <stdio.h>
struct n {
int *p;
};
int main(void) {
int i = 8;
struct n m;
m.p = &i;
printf("%d ", i);
printf("%d", *(m.p));
return 0;
}
The output is "8 8".
There is no need for garbage collection or the other types of pointers which I have read about.
I've tried this:
struct n {
p: *mut int
}
fn main() {
let mut i: int = 8;
let mut m: n;
m.p = &i;
println!("{} ", i);
println!("{}", *(m.p));
}
But I get:
error: mismatched types: expected `*mut int`, found `&int` (expected *-ptr, found &-ptr).
Relating to this error:
m.p = &i;
There are no errors for the other lines.
I read that & is to get the address of a variable, but how can I store an address?
Upvotes: 0
Views: 4770
Reputation: 16630
Change m.p = &i;
to m.p = &mut i as *mut _;
A more idiomatic way would be this though:
let mut m = n {
p: &mut i
};
And even more idiomatic would be not using a raw pointer unless necessary.
struct N<'a> {
p: &'a mut int
}
Upvotes: 1