Reputation: 407
I am learning Rust and I am trying to write a simple IP handling function
enum IpAddr{
v4(u8,u8,u8,u8),
v6(String),
}
impl IpAddr{
fn write(&self){
match *self {
IpAddr::v4(A,B,C,D) => println!("{}.{}.{}.{}",A,B,C,D),
IpAddr::v6(S) => println!("{}",S)
}
}
}
The v4 matches fine, but I get the following build error on the 2nd one
error[E0507]: cannot move out of
self.0
which is behind a shared reference
move occurs because
_S
has typeString
, which does not implement theCopy
trait
How can I match on a enum with a String attached?
Upvotes: 3
Views: 572
Reputation: 5613
I'm not sure why you're matching on *self
, as it does not appear to be necessary, but if you really need to do that for some reason, you can also solve the problem by using the ref
keyword with your variable (ref s
), which will cause the value to be borrowed instead of moving it.
enum IpAddr{
V4(u8,u8,u8,u8),
V6(String),
}
impl IpAddr{
fn write(&self){
match *self {
IpAddr::V4(a,b,c,d) => println!("{}.{}.{}.{}",a,b,c,d),
IpAddr::V6(ref s) => println!("{}", s)
}
}
}
Upvotes: 3
Reputation: 3424
Its complaining because you are trying to copy self
by dereferencing, but IpAddr
contains a String
which is not copy-able.
Remove the dereference and it should work as expected
match self {
IpAddr::v4(A,B,C,D) => println!("{}.{}.{}.{}",A,B,C,D),
IpAddr::v6(S) => println!("{}",S)
}
Upvotes: 3