variables - Go err : cannot use cur (type *user. User) 作为 f.WriteString 参数中的类型字符串

标签 variables go

如何将数据转换为 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/

相关文章:

java - JCombobox1与json数据转换静态变量

variables - AWK 通过传递变量在特定行替换模式

golang gocql.NewCluster 未定义没有字段或方法

string - MATLAB 字符串变量

java - 无法从 Java 中的另一个类访问变量?

c++ - 如何在没有setter的情况下设置类内部类的成员变量?

variables - 为什么可以使用 for 循环声明同一个变量两次?

go - 如何使用索引构造翻转的单个位位域?

go - 指向非复合文字的指针

go - Go 中的 128 位 float - 相当于 C#'s "十进制“类型