Home Go err: cannot use cur (type *user.User) as type string in argument to f.WriteString
Reply: 1

Go err: cannot use cur (type *user.User) as type string in argument to f.WriteString

Jack Smith
1#
Jack Smith Published in 2017-11-12 16:30:05Z

How do I convert data to a string type? I need to write down the data I need to the file which is either not a variable, how do I do it?

Code:

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)
        }
    }
}

I do not need to use the cur.Username field. Only a variable.

icza
2#
icza Reply to 2017-11-12 17:02:02Z

File.WriteString() expects a string argument, yet you attempt to pass cur to it which is of type *user.User, a pointer to a struct. This is obviously a compile-time error.

user.User is a struct with the following definition:

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
}

Choose what you want to output to the file, most likely the Username field or maybe the Name field. These are fields of string type, so these you can pass without a problem:

if _, err = f.WriteString(cur.Username); err != nil {
    panic(err)
}

If you want to write out the complete User struct, you may use the fmt package, conveniently the fmt.Fprint() or fmt.Fprintf() functions:

if _, err = fmt.Fprintf(f, "%+v", cur); err != nil {
    panic(err)
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303581 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO