簡體   English   中英

為什么我不能將字符串附加到字節切片作為Go引用指定?

[英]Why can't I append string to byte slice as the Go reference specified?

引用Go的append引用

作為一種特殊情況,將字符串附加到字節切片是合法的,如下所示:
slice = append([]byte("hello "), "world"...)

但我覺得我不能這樣做,因為這個片段:

package main
import "fmt"

func main(){
    a := []byte("hello")
    s := "world"
    a = append(a, s) //*Error*: can't use s(type string) as type byte in append 
    fmt.Printf("%s",a)
}

我做錯了什么?

您需要使用“...”作為后綴才能將切片附加到另一個切片。 像這樣:

package main
import "fmt"

func main(){
    a := []byte("hello")
    s := "world"
    a = append(a, s...) // use "..." as suffice 
    fmt.Printf("%s",a)
}

你可以在這里試試: http//play.golang.org/p/y_v5To1kiD

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM