登录
首页 >  Golang >  Go问答

为什么在将变量分配给Scanln函数的err参数时,我无法将其转换为WriteFile函数中的字节数据?

来源:stackoverflow

时间:2024-02-10 12:09:22 352浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《为什么在将变量分配给Scanln函数的err参数时,我无法将其转换为WriteFile函数中的字节数据?》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

为什么 fmt.scanln 函数需要一个错误 err 变量? 我还需要帮助理解 fmt.writeln 参数的用途。

该程序的目的是通过命令行获取用户输入的数据,并将其输出到文件go-log.go

package main

import ("fmt"
        "os")

func main() {

  YNQ := "yes"

  for YNQ == "yes" {

    fmt.Println("What do you want to add to the log?")

    openfile, err := os.Open("go-log.txt")

    addedText, err := fmt.Scanln()

    os.WriteFile("go-log.txt", []byte(addedText), 0666)

    //add date and time here

    fmt.Println("Would you like to add anything else?")

    fmt.Scanln(&YNQ)
  }
  openfile.Close()
}
  
 - errors recieved:
   
       -cannot convert addedText (type int) to type [byte]
       -undefined: openfile

正确答案


首先,让我们使用 go fmt 命令使代码可读:

package main

import (
    "fmt"
    "os"
)

func main() {
    ynq := "yes"
    for ynq == "yes" {
        fmt.println("what do you want to add to the log?")
        openfile, err := os.open("go-log.txt")
        addedtext, err := fmt.scanln()
        os.writefile("go-log.txt", []byte(addedtext), 0666)
        //add date and time here
        fmt.println("would you like to add anything else?")
        fmt.scanln(&ynq)
    }
    openfile.close()
}

其次,让我们尝试理解并回答您的问题。你问的是:

  1. go 编译器强制您将所有返回值分配给变量,或者不分配任何返回值。您还可以使用占位符 _ 标记您对此变量不感兴趣。请阅读本文了解更多信息:https://gobyexample.com/multiple-return-values
  2. scanln 返回错误,因为扫描标准输出时可能会出现错误。

fmt中没有函数writelnhttps://pkg.go.dev/fmt#pkg-index

请仔细阅读 fmt.scanln 函数的文档:https://pkg.go.dev/fmt#Scanln。它不返回文本。它将从 stdin 读取的内容写入其参数。这些参数应该是指向您要填充的变量的指针:https://www.geeksforgeeks.org/fmt-scanln-function-in-golang-with-examples/

openfile 变量在此范围内确实不可用。请阅读这篇关于 go 中作用域的文章:https://medium.com/golangspec/scopes-in-go-a6042bb4298c

程序应该如下所示:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    f, err := os.OpenFile("go-log.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()

    YNQ := "yes"
    for YNQ == "yes" {
        fmt.Println("What do you want to add to the log?")
        
        scanner := bufio.NewScanner(os.Stdin)
        var line string
        if scanner.Scan() {
            line = scanner.Text()
        } else {
            log.Fatalln("Cannot read from stdin.")
        }
        
        if _, err = f.WriteString(line + "\n"); err != nil {
            log.Fatalln(err)
        }
        
        fmt.Println("Would you like to add anything else?")
        _, err := fmt.Scanln(&YNQ)
        if err != nil {
            log.Fatalln(err)
        }
    }
}

到这里,我们也就讲完了《为什么在将变量分配给Scanln函数的err参数时,我无法将其转换为WriteFile函数中的字节数据?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>