3 回答

TA貢獻2016條經驗 獲得超9個贊
調試目的需要這種輸出。
有什么辦法,我們可以像下面這樣直接使用并獲取值來讀取指針切片內的值fmt.Printf?
users []*user
fmt.Printf("users at slice %v \n", users)
users at slice [&{1 cooluser1 [email protected]}, &{2 cooluser2 [email protected]}]
包 fmt
import "fmt"
縱梁型
Stringer 由具有 String 方法的任何值實現,該方法定義該值的“本機”格式。String 方法用于打印作為操作數傳遞給任何接受字符串的格式或未格式化打印機(如 Print)的值。
type?Stringer?interface?{ ????????String()?string}
調試目的需要這種輸出。
有什么辦法,我們可以像下面這樣直接使用并獲取值來讀取指針切片內的值fmt.Printf?
users []*user
fmt.Printf("users at slice %v \n", users)
users at slice [&{1 cooluser1 [email protected]}, &{2 cooluser2 [email protected]}]
包 fmt
import "fmt"
縱梁型
Stringer 由具有 String 方法的任何值實現,該方法定義該值的“本機”格式。String 方法用于打印作為操作數傳遞給任何接受字符串的格式或未格式化打印機(如 Print)的值。
type Stringer interface {
? ? ? ? String() string
}
例如,
package main
import (
? ? "fmt"
)
type user struct {
? ? userID int
? ? name? ?string
? ? email? string
}
type users []*user
func (users users) String() string {
? ? s := "["
? ? for i, user := range users {
? ? ? ? if i > 0 {
? ? ? ? ? ? s += ", "
? ? ? ? }
? ? ? ? s += fmt.Sprintf("%v", user)
? ? }
? ? return s + "]"
}
func addUsers(users users) {
? ? users = append(users, &user{userID: 1, name: "cooluser1", email: "[email protected]"})
? ? users = append(users, &user{userID: 2, name: "cooluser2", email: "[email protected]"})
? ? fmt.Printf("users at slice %v \n", users)
}
func main() {
? ? var users users
? ? addUsers(users)
}
游樂場:https://play.golang.org/p/vDmdiKQOpqD
輸出:
users at slice [&{1 cooluser1 [email protected]}, &{2 cooluser2 [email protected]}]?

TA貢獻1859條經驗 獲得超6個贊
代碼: https: //play.golang.org/p/rBzVZlovmEc
輸出 :
切片用戶 [{1 cooluser1 [email protected]} {2 cooluser2 [email protected]}]
使用縱梁你可以實現它。
參考: https: //golang.org/pkg/fmt/#Stringer
package main
import (
"fmt"
)
type user struct {
userID int
name string
email string
}
func (t user) String() string {
return fmt.Sprintf("{%v %v %v}", t.userID, t.name, t.email)
}
func main() {
var users []*user
addUsers(users)
}
func addUsers(users []*user) {
users = append(users, &user{userID: 1, name: "cooluser1", email: "[email protected]"})
users = append(users, &user{userID: 2, name: "cooluser2", email: "[email protected]"})
printUsers(users)
}
func printUsers(users []*user) {
fmt.Printf("users at slice %v \n", users)
}
您不需要將 stringer 應用于用戶,即 []*users 相反,如果您只為單個用戶執行此操作,它就可以正常工作。它還減少了您需要手動執行的字符串操作,使您的代碼更加優雅。

TA貢獻1820條經驗 獲得超10個贊
您可以使用spew
go get -u github.com/davecgh/go-spew/spew
func spewDump(users []*user) {
_, err := spew.Printf("%v", users)
if err != nil {
fmt.Println("error while spew print", err)
}
}
輸出:
[<*>{1 cooluser1 [email protected]} <*>{2 cooluser2 [email protected]}]
- 3 回答
- 0 關注
- 176 瀏覽
添加回答
舉報