2017-11-12 4 views
1

データをstringタイプに変換するにはどうすればよいですか?私はdataを書き留める必要があります。私は変数ではないファイルにする必要がありますどうすればいいですかGo err:f.WriteStringの引数にcur(type * user.User)をタイプ文字列として使用できません

コード:

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フィールドを使用する必要はありません。変数のみ。

+0

curとは何ですか? 'struct'はどうですか?どのデータをファイルに保存しますか? – nicovank

+0

@nicovank cur、err:= user.Current()を文字列として使用する必要があります。出力ファイルをファイル –

+0

インポートパッケージ 'fmt'にインポートし、' f.WriteString(fmt.Sprintf( "%+ v \ n"、cur)) ' – mkopriva

答えて

6

File.WriteString()string引数を受け取りますが、の構造体へのポインタであるcurを渡そうとします。これは明らかにコンパイル時エラーです。

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) 
} 
関連する問題