英文:
Error in opening and writing to a file
问题
我想打开一个文件并向其中写入一些文本,但是我遇到了以下错误:
.\hello.go:13: cannot use msg (type string) as type []byte in argument to f.Write
以下是我目前的代码:
package main
import (
"os"
)
func printer(msg string) (err error) {
f, err := os.Create("helloworld.txt")
if err != nil {
return err
}
defer f.Close()
f.Write(msg)
return err
}
func main() {
printer("Hello World")
}
英文:
I want to open a file and write some text to it, however I get the following error:
.\hello.go:13: cannot use msg (type string) as type []byte in argument to f.Write
Here's my code so far:
package main
import (
"os"
)
func printer(msg string) (err error) {
f, err := os.Create("helloworld.txt")
if err != nil {
return err
}
defer f.Close()
f.Write(msg)
return err
}
func main() {
printer("Hello World")
}
答案1
得分: 5
使用io.WriteString(f, msg)
、f.Write([]byte(msg))
或io.Copy(f, strings.NewReader(msg))
。
英文:
Use io.WriteString(f, msg)
, f.Write([]byte(msg))
or io.Copy(f, strings.NewReader(msg))
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论