gpt4 book ai didi

go - 如果 Println 出错,如果可以将其作为变量,如何显示 Println 的错误值?

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:24 28 4
gpt4 key购买 nike

它说:

Printf 根据格式说明符格式化并写入标准输出。它返回写入的字节数和遇到的任何写入错误。

如果错误存储在 b 中,如何创建/测试错误并显示错误当我运行程序时它显示“nil”,因为没有错误,我如何显示任何错误?

  a,b :=fmt.Println("Hello, playground")
fmt.Println(a)
fmt.Println(b)

https://golang.org/pkg/fmt/#Println
func Println(a ...interface{}) (n int, err error)
https://play.golang.org/p/8Cjb2Sfunx7

最佳答案

有 Println 错误是不常见的,文档也是如此。但是,如果您真的有兴趣对其进行测试,它会起作用:

package main

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

func main() {
const name, age = "Kim", 22
os.Stdout.Close()
_, err := fmt.Println(name, "is", age, "years old.")
log.Fatal(err)

}

为了人为触发错误,我们关闭了 Println 使用的默认 Stdout 文件。查看os documentation .

关于go - 如果 Println 出错,如果可以将其作为变量,如何显示 Println 的错误值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57192666/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com