Reputation: 115
use std::net::{TcpListener, TcpStream};
pub struct Server {
addr: String,
}
impl Server{
pub fn new(addr: String) -> Self {
Self {
addr: addr
}
}
pub fn run(&self) { // can make this (self) since we can give ownership of addr to run function.
println!("Listening on: {}", self.addr);
let listener = TcpListener::bind(self.addr);
}
}
I am new to rust so please forgive the ignorance. I am trying to pass a reference of self.addr to the TcpListener but it is throwing this error:
cannot move out of `self.addr` which is behind a shared reference
move occurs because `self.addr` has type `String`, which does not implement the `Copy` trait
When I change it to
let listener = TcpListener::bind(&self.addr);
it works. I thought that &self was already a reference to the variable self.addr which I am trying to use. So why do I need to reference it again for the TcpListener?
Upvotes: 1
Views: 185
Reputation: 71005
self
is a reference. self.addr
is not.
When you access self.addr
, you dereference self
. self.addr
has type String
, not &String
. If you want a reference (or to not move it), you need to take a reference explicitly.
Upvotes: 1