无法将[]byte分配给z(类型为string)进行多重赋值。

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

Cannot assign []byte to z (type string) in multiple assignment

问题

我正在尝试查找文件夹中的文件内容,所以我列出了文件夹中的内容,然后在循环中尝试读取文件。

files, _ := ioutil.ReadDir("documents/")
for _, f := range files {
    //fmt.Println(f.Name())

    z := "documents/" + f.Name()
    fmt.Println(z) // 递归打印出'documents/*文件名*'
    z, err := ioutil.ReadFile(z) // 这一行引发了错误

我得到的错误是:test.go:85: 在多重赋值中,无法将[]byte分配给z(类型为string)。

英文:

I'm trying to find the contents of files within a folder, so I'm listing what's in the folder then while looping through it I'm trying to read the files.

files, _ := ioutil.ReadDir("documents/")
for _, f := range files {
		//fmt.Println(f.Name())

	z := "documents/" + f.Name()
	fmt.Println(z) // prints out 'documents/*doc name*' recursively
	z, err := ioutil.ReadFile(z) // This line throws up the error

The error I get is: test.go:85: cannot assign []byte to z (type string) in multiple assignment.

答案1

得分: 7

你可以将[]byte转换为字符串,但是你不能将多返回值函数的一个值转换为字符串。

buf, err := ioutil.ReadFile(z)
if err != nil {
        log.Fatal(err)
}
z = string(buf)

然而,通常最好不要将二进制数据转换为字符串,而是直接使用buf进行操作。

英文:

You can convert []byte to string, but you cannot convert one value of a multiple return valued function.

buf, err := ioutil.ReadFile(z)
if err != nil {
        log.Fatal(err)
}
z = string(buf)

However, quite often it's better to not convert binary data to strings and work directly with buf.

huangapple
  • 本文由 发表于 2013年7月3日 22:00:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/17450062.html
匿名

发表评论

匿名网友

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

确定