Linuxea
Linuxea

Reputation: 329

golang byte and string Sometimes compatible and sometimes incompatible

This is my golang code


package test

import (
    "fmt"
    "testing"
)

func TestOne(t *testing.T) {

    bytes := make([]byte, 0)
    bytes = append(bytes, 1, 2, 3)            // pass
    bytes = append(bytes, []byte{1, 2, 3}...) // pass
    bytes = append(bytes, "hello"...)          // pass too, ok. reference: As a special case, it is legal to append a string to a byte slice

}

func TestTwo(t *testing.T) {

    printBytes([]byte{1, 2, 3}...) // pass
    printBytes("abcdefg"...)       // fail

}

func printBytes(b ...byte) {
    fmt.Println(b)
}


These are some code in strings.Builder

func (b *Builder) WriteString(s string) (int, error) {
    b.copyCheck()
    b.buf = append(b.buf, s...)
    return len(s), nil
}

The param s can be regards as slice type when be used in function append .

But I defined a function printBytes like append,

when I invoke like this

printBytes("abcdefg"...)

The "abcdefg" seems like not be regards as a type slice

Upvotes: 2

Views: 254

Answers (1)

Hymns For Disco
Hymns For Disco

Reputation: 8395

From the append documentation:

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)

Other than this special case (and a similar case for copy), string is not treated like a slice type in Go.

"Built-in" functions like this are allowed to have special cases that don't strictly follow the general type rules in Go, because their behaviour is actually part of the language specification itself. See Appending to and copying slices.

Upvotes: 7

Related Questions