3

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,
            }
5
  • 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? Commented Jun 20, 2020 at 2: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. Commented Jun 20, 2020 at 2: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. Commented Jun 20, 2020 at 10:48
  • 1
    Does this answer your question? How do I collect into an array? Commented Jun 20, 2020 at 11:09
  • @E_net4likesfun thanks, so it seems it isn't possible Commented Jun 20, 2020 at 12:13

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.