Struct và interface
Go Structs
Group related values into your own type with named fields.
Bạn sẽ học được gì
- Defining a struct
- Fields and %+v
- Structs are copied
User
Name"Ada"Age37ActivetrueYour own type with named fields
A struct is a type you define by naming its fields. It keeps related data together, such as the name, age and status of a user.
Fields are read and changed with a dot. %v prints the values and %+v adds the field names. Assigning a struct copies it, so changing guest does not change user. A struct can also be declared in place without a name.
Những điểm quan trọng
- Fields are read and changed with a dot.
- %+v prints the field names too.
- Assigning a struct copies it.
Ví dụ Go chạy được
main.go
package main
import "fmt"
type User struct {
Name string
Age int
Active bool
}
func main() {
user := User{Name: "Ada", Age: 36, Active: true}
user.Age++
fmt.Println(user.Name, user.Age)
fmt.Printf("%v\n%+v\n", user, user)
guest := user // structs are copied on assignment
guest.Name = "Guest"
fmt.Println(user.Name, guest.Name)
point := struct{ X, Y int }{3, 4}
fmt.Println(point.X + point.Y)
}
Ada 37
{Ada 37 true}
{Name:Ada Age:37 Active:true}
Ada Guest
7Luyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
Tất cả thử thách