2

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,
            }
Will
  • 1,059
  • 2
  • 10
  • 22
  • What do you mean by into an array? Returning an array of variable size is not possible in rust. Would a vec of chars solve your problem? – user1937198 Jun 20 '20 at 02:28
  • 2
    Is the string hardcoded? Because you can do `b"1.1.1.1"` to make an array which contains the bytes. Otherwise I'd look into the `.chars()` method. – Optimistic Peach Jun 20 '20 at 02:50
  • @user1937198 the str is of fixed length, I have a struct with a field that contains an array, otherwise I'd use a vec. I can't use a vec since it is inside a struct. – Will Jun 20 '20 at 10:48
  • 1
    Does this answer your question? [How do I collect into an array?](https://stackoverflow.com/questions/26757355/how-do-i-collect-into-an-array) – E_net4 Jun 20 '20 at 11:09
  • @E_net4likesfun thanks, so it seems it isn't possible – Will Jun 20 '20 at 12:13

1 Answers1

3

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);
Kitsu
  • 3,166
  • 14
  • 28