user2881914
user2881914

Reputation: 407

Matching on a enum String

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 type String, which does not implement the Copy trait

How can I match on a enum with a String attached?

Upvotes: 3

Views: 572

Answers (2)

Herohtar
Herohtar

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) 
        }
    }
}

Playground

Upvotes: 3

pigeonhands
pigeonhands

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

Related Questions