如何将数据转换为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)
}
}
}
我不需要使用cur.Username
字段。只有一个变量。
答案 0 :(得分: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
}
是一个具有以下定义的结构:
Username
选择要输出到文件的内容,很可能是Name
字段或string
字段。这些是if _, err = f.WriteString(cur.Username); err != nil {
panic(err)
}
类型的字段,因此您可以毫无问题地通过这些字段:
User
如果您想写出完整的if _, err = fmt.Fprintf(f, "%+v", cur); err != nil {
panic(err)
}
结构,可以使用fmt
包,方便的fmt.Fprint()
或fmt.Fprintf()
功能:
public function index(Request $request)
{
// if param exists, call function from another controller
if($request->has('callAnotherMethod')){
return app('App\Http\Controllers\yourControllerHere')->index();
}
$comproducts = Comproduct::paginate(6);
$items = Item::orderBy('name')->get();
return view('computer', compact(['comproducts', 'items']));
}