如何将数据转换为 string
类型?我需要将我需要的数据
写到不是变量的文件中,我该怎么做?
代码:
package main
import "os"
import "os/user"
import "encoding/json"
func main(){
f, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
panic(err)
}
defer f.Close()
cur, err := user.Current()
if err != nil {
} else {
if _, err = f.WriteString(cur); err != nil {
panic(err)
}
}
}
我不需要使用 cur.Username
字段。只是一个变量。
最佳答案
File.WriteString()
需要一个 string
参数,但您尝试将 cur
传递给它,类型为 *user.User
,指向结构的指针。这显然是一个编译时错误。
user.User
是一个具有以下定义的结构体:
type User struct {
// Uid is the user ID.
// On POSIX systems, this is a decimal number representing the uid.
// On Windows, this is a security identifier (SID) in a string format.
// On Plan 9, this is the contents of /dev/user.
Uid string
// Gid is the primary group ID.
// On POSIX systems, this is a decimal number representing the gid.
// On Windows, this is a SID in a string format.
// On Plan 9, this is the contents of /dev/user.
Gid string
// Username is the login name.
Username string
// Name is the user's real or display name.
// It might be blank.
// On POSIX systems, this is the first (or only) entry in the GECOS field
// list.
// On Windows, this is the user's display name.
// On Plan 9, this is the contents of /dev/user.
Name string
// HomeDir is the path to the user's home directory (if they have one).
HomeDir string
}
选择要输出到文件的内容,最有可能是 Username
字段或 Name
字段。这些是 string
类型的字段,因此您可以毫无问题地传递这些字段:
if _, err = f.WriteString(cur.Username); err != nil {
panic(err)
}
如果你想写出完整的 User
结构,你可以使用 fmt
包,方便fmt.Fprint()
或 fmt.Fprintf()
功能:
if _, err = fmt.Fprintf(f, "%+v", cur); err != nil {
panic(err)
}
关于variables - Go err : cannot use cur (type *user. User) 作为 f.WriteString 参数中的类型字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47251170/