Golang how to convert string slice to string?

huangapple go评论95阅读模式
英文:

Golang how to convert string slice to string?

问题

这是错误信息:

ubuntu@buildserver:~/gospace$ go build src/runk/test.go
# command-line-arguments
src/runk/test.go:8: 无法将 myvar(类型 []string)转换为类型 string
ubuntu@buildserver:~/gospace$

这是代码:

ubuntu@buildserver:~/gospace$ cat src/run/test.go
package main

func Test() string {

	var myvar []string
	myvar = append(myvar, "hello world")

	return string(myvar)

}

func main() {
	Test()
}
ubuntu@buildserver:~/gospace$
英文:

Here's the error:

ubuntu@buildserver:~/gospace$ go build src/runk/test.go
# command-line-arguments
src/runk/test.go:8: cannot convert myvar (type []string) to type string
ubuntu@buildserver:~/gospace$

Here's the code:

ubuntu@buildserver:~/gospace$ cat src/run/test.go
package main

func Test() string {

	var myvar []string
	myvar = append(myvar, "hello world")

	return string(myvar)

}

func main() {
	Test()
}
ubuntu@buildserver:~/gospace$

答案1

得分: 4

myvar是一个字符串切片,你想要一个单独的字符串?如果你只是想要将它们连接起来,你可以使用strings.Join(myvar,"")

或者一开始就不要创建一个字符串切片:

myvar := ""
myvar += "hello, world!"
return myvar
英文:

myvar is a slice of strings, and you want a single string? If you just want to concatinate them you can use strings.Join(myvar,"").

Or not make a string slice in the first place:

myvar := ""
myvar += "hello, world!"
return myvar

huangapple
  • 本文由 发表于 2015年10月21日 08:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/33249076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定