错误:不能使用cur(type*user.User)作为f.WriteString参数中的类型字符串

Jac*_*ith 1 variables go

如何将数据转换为string类型?我需要写下data我需要的文件,这不是一个变量,我该怎么做

码:

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我不需要使用该cur.Username字段.只有一个变量.

icz*_*cza 6

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
}
Run Code Online (Sandbox Code Playgroud)

选择要输出到文件的内容,最有可能是Username字段或Name字段.这些是string类型的字段,因此您可以毫无问题地传递:

if _, err = f.WriteString(cur.Username); err != nil {
    panic(err)
}
Run Code Online (Sandbox Code Playgroud)

如果你想写出完整的User结构,你可以使用fmt包,方便的fmt.Fprint()或者fmt.Fprintf()功能:

if _, err = fmt.Fprintf(f, "%+v", cur); err != nil {
    panic(err)
}
Run Code Online (Sandbox Code Playgroud)