3 ms·
Since "localhost" isn't assigned to a variable, couldn't it be a safe implicit conversion?
by http-teapot 6y ago
Since "localhost" isn't assigned to a variable, couldn't it be a safe implicit conversion?
- PudgePacket 6y agoIt's not really important whether it's assigned to a variable or not. It's important that "potentially expensive" operations like memory allocation are obvious. So you either need to call to_string, or call String::new("localhost").
- twic 6y agoThe thing is, "localhost" ends up being some characters [1] in the read-only section of the binary. You can safely read that, but you can't modify it or delete it (that won't work, and if it did work, it would make a hell of a mess!). So this is fine: let host: &str = "localhost"; Because a &str is just a read-only pointer to some characters [1], and you're just setting host to be a pointer to those characters in the read-only section. But this is not: let host: String = "localhost"; Because a String is not just a pointer, it's a pointer which implies ownership of an allocation on the heap [1]. That means you can modify the contents of a String, and when the String is dropped, that allocation will be freed. You can't just set up a String using a pointer into the read-only section. You need to make an allocation, copy the characters into it, and use that. Which is what str::to_string() does. [1] And a length, but we can ignore that for now.