Reputation: 1169
how would I go about changing a str into a array of bytes or chars?
for example:
"1.1.1.1" -> ["1", ".", "1", ".", "1", ".", "1"]
The string is an ip so no usual characters.
I have tried doing try_into()
but got
expected array `[u8; 10]`
found struct `std::slice::Iter<'_, u8>`
Any guidance would be appreciated.
Edit: In my use case I have a struct called Player:
struct Player {
cards: [i32, 2],
chips: u32,
ip: [u8; 10],
folded: bool,
hand: u8,
}
And I'd like to set the id to a string that would be received and store it as a array. Ideally the struct would impl
copy, so a vec
can't be used.
a player being made:
Player {
cards: [4,5],
chips: 500,
ip: "localhost", // how to change this to an array
folded: false,
hand: 0,
}
Upvotes: 3
Views: 4306
Reputation: 3435
str
is a special case for a slice
type. And unlike an array it does not have a known size at compile-time (i.e. calculated dynamically during program execution), therefore there is no infallible conversion. But you can manually craft an array and iterate over str
to get it bytes:
let s = "1.1.1.1";
let mut your_array = [0u8; 10];
if s.len() != your_array.len() {
// handle this somehow
}
s.bytes()
.zip(your_array.iter_mut())
.for_each(|(b, ptr)| *ptr = b);
Upvotes: 3