Go cơ bản

Go Data Types: int, float64, bool, rune, string

The basic types of Go, how to print them with Printf, and why conversions are always written out.

  • Cơ bản
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • int, float64, bool, string
  • rune
  • Explicit conversions
Value → type
30int
19.99float64
truebool
'G'rune (int32)

One type per variable

Go is statically typed: every variable has one type that never changes. The types you will use most are int, float64, bool, string and rune, which is one Unicode character.

Go never converts numbers for you, so float64(age) is needed before adding a float. Printf formats values with verbs: %d for integers, %.2f for two decimals, %t for booleans, %c for a character and %T for the type. A rune is another name for int32.

Những điểm quan trọng

  1. Go never converts numbers for you: write float64(age).
  2. A rune is one Unicode character.
  3. %T prints the type of a value.

Ví dụ Go chạy được

Go
Chạy code →
main.go
package main

import "fmt"

func main() {
	var age int = 30
	var price float64 = 19.99
	var ready bool = true
	var initial rune = 'G'
	var name string = "Gopher"

	total := float64(age) + price // conversions are always explicit
	fmt.Printf("%d %.2f %t %c %s\n", age, price, ready, initial, name)
	fmt.Printf("total = %.2f\n", total)
	fmt.Printf("%T %T %T\n", age, price, initial)
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
30 19.99 true G Gopher
total = 49.99
int float64 int32

Luyệ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.

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