Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

string - How do I convert a single byte to a []byte


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This seems to be what you're actually trying to do:

    characters := "some text"
    for i := 0; i < len(characters); i++ {
        b := characters[i]
        fmt.Println(b)
    }

Your code is confusing (and doesn't compile), but you appear to want to iterate over the string, and for the element you are currently on, convert the character to a byte and print it. If so, you don't need (or want) to convert anything to a []byte.


If you don't want to iterate byte by byte but instead character by character, use a range loop. It iterates over runes:

    characters := "s?me spécial text"
    for _, r := range characters {
        char := string(r)
        b := []byte(char)
        fmt.Println(char, b)
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...