Basic Data Types
Go has basic data types including integers, floating-point numbers, strings, and booleans. Each type has a clearly defined size and purpose.
Syntax List
| Type | Description |
|---|---|
| int / int8 / int16 / int32 / int64 | Signed integer types. int is platform-dependent and is 64-bit on 64-bit environments. |
| uint / uint8 / uint16 / uint32 / uint64 | Unsigned integer types. They cannot hold negative values, but their positive range is twice that of signed types. |
| float32 / float64 | Floating-point number types. Use float64 for higher precision in most cases. |
| complex64 / complex128 | Complex number types. Each value has a real part and an imaginary part. |
| string | A string type. It is an immutable sequence of bytes encoded in UTF-8. |
| bool | A boolean type. Its value is either true or false. |
| byte | An alias for uint8. Used when working with raw byte data. |
| rune | An alias for int32. Represents a Unicode code point (a single character). |
Sample Code
sample_basic_types.go
package main
import "fmt"
func main() {
// Integer types
var age int = 25
var score int64 = 9876543210
// Floating-point types
var price float64 = 1980.5
var ratio float32 = 3.14
// String type
var name string = "Itadori Yuji"
greeting := "Hello, " + name + "!"
// Boolean type
var isActive bool = true
// byte and rune
var b byte = 'A' // ASCII code 65
var r rune = 'é' // Unicode code point U+00E9
fmt.Println(age, score)
fmt.Printf("%.1f / %.2f\n", price, ratio)
fmt.Println(greeting)
fmt.Println(isActive)
fmt.Printf("byte: %d, rune: %d\n", b, r)
// String length in bytes vs. number of characters
s := "café"
fmt.Println(len(s)) // Byte length: 5 (é is 2 bytes in UTF-8)
fmt.Println(len([]rune(s))) // Character count: 4
}
This produces the following output:
go run basic_types.go 25 9876543210 1980.5 / 3.14 Hello, Itadori Yuji! true byte: 65, rune: 233 5 4
Notes
Go's integer types include those with an explicit size and the platform-dependent int. In most cases int is sufficient, but specifying an explicit size is important when doing binary operations or communicating with external APIs.
Because string is a byte sequence, len() returns the byte count for multibyte characters such as accented letters or emoji. To work with the correct character count, convert the string to []rune(s) first.
Type conversion is never implicit in Go, so arithmetic between different types requires an explicit type conversion.
If you find any errors or copyright issues, please contact us.