Unterschied zwischen einem Slice und einem Array ist dieser, dass ein Slice eine unbestimmte Anzahl Elemente enthält, und ein Array eine bestimmte Anzahl Elemente.
var users []User // slice
var users [5]User // array
users := make([5]User{}) // array
var users []user
var funcUser = new(user)
funcUser.id = uuid.New().String()
funcUser.username = username
funcUser.firstname = firstname
funcUser.lastname = lastname
funcUser.email = email
funcUser.token = token
users = append(users, funcUser)
// for Export the struct -> name must be uppercase: user -> User, id -> Id, ...
type user struct {
id string `json:"id"`
firstname string `json:"firstname"`
lastname string `json:"lastname"`
email string `json:"email"`
username string `json:"username"`
token string `json:"token"`
}
// Print a whole Slice
fmt.Println("%v", users)
// OR
for i := 0; i < len(users); i++ {
fmt.Println(users[i])
}
// Create and insert data into Slice
names := []string{"Mattia", "Mauro", "Milena", "Gian-Liun"}
How to print the values of slices
json.Marshal(struct) returns "{}"
3 Ways to Update Elements in a Slice
var users []user
r.GET("/getusers", func(c *gin.Context) {
c.JSON(200, users)
})