ZetCode

Golang int16 类型

最后修改时间 2025 年 5 月 8 日

本教程将解释如何在 Go 中使用内置的 int16 类型。我们将通过实际示例涵盖 16 位整数的基本概念。

int16 类型在 Go 中代表有符号的 16 位整数。它可以存储从 -32768 到 32767 的值。当内存效率很重要时,此类型非常有用。

在 Go 中,int16 是几种具有特定大小的整数类型之一。它占用确切的 2 字节内存,这比默认的 int 小。

基本的 int16 声明和初始化

使用 int16 最简单的方法是声明和初始化变量。此示例展示了带显式类型的基本变量声明。
注意: Go 中的默认整数类型是 int,而不是 int16

basic_int16.go
package main

import "fmt"

func main() {

    var a int16 = 32767 // Maximum positive value
    var b int16 = -32768 // Minimum negative value
    c := int16(1000) // Type conversion from literal
    
    fmt.Println("a:", a)
    fmt.Println("b:", b)
    fmt.Println("c:", c)
}

我们声明了三个具有不同初始化方法的 int16 变量。该示例显示了所有可能值的范围。

int16 的算术运算

int16 支持所有标准的算术运算。此示例演示了加法、减法、乘法和除法。

arithmetic_int16.go
package main

import "fmt"

func main() {

    x := int16(15000)
    y := int16(8000)
    
    sum := x + y
    diff := x - y
    product := x * y
    quotient := x / y
    
    fmt.Println("Sum:", sum)
    fmt.Println("Difference:", diff)
    fmt.Println("Product:", product)
    fmt.Println("Quotient:", quotient)
}

所有运算都保留 int16 类型。请注意溢出问题,因为 Go 在算术运算中不会自动提升类型。

int16 的类型转换

int16 和其他数值类型之间进行转换需要显式转换。此示例展示了安全的类型转换实践。

conversion_int16.go
package main

import "fmt"

func main() {

    var i16 int16 = 20000
    var i32 int32 = 50000
    
    // Convert int16 to int32 (safe)
    convertedUp := int32(i16)
    
    // Convert int32 to int16 (may lose data)
    convertedDown := int16(i32)
    
    fmt.Println("Original int16:", i16)
    fmt.Println("Converted to int32:", convertedUp)
    fmt.Println("Converted back to int16:", convertedDown)
    
    // Float conversion
    f := 123.45
    floatConverted := int16(f)
    fmt.Println("Float converted to int16:", floatConverted)
}

转换为较大的类型总是安全的,但向下转换可能会截断数据。在转换类型时,请始终检查值范围。

在数组和切片中使用 int16

int16 在集合中特别有用,可以节省内存。此示例演示了带有 int16 元素的数组和切片。

collections_int16.go
package main

import "fmt"

func main() {

    // Array of int16 values
    arr := [5]int16{10, 20, 30, 40, 50}
    fmt.Println("Array:", arr)
    
    // Slice of int16 values
    slice := []int16{100, 200, 300, 400}
    fmt.Println("Original slice:", slice)
    
    // Append to slice
    slice = append(slice, 500, 600)
    fmt.Println("Appended slice:", slice)
    
    // Memory efficient large slice
    largeSlice := make([]int16, 0, 10000)
    fmt.Printf("Large slice len: %d, cap: %d\n", 
        len(largeSlice), cap(largeSlice))
}

与默认的 int 类型相比,在大型集合中使用 int16 可以显着减少内存使用。

边缘情况和溢出处理

int16 的范围有限,因此溢出是一个问题。此示例显示了如何检测和处理潜在的溢出情况。

overflow_int16.go
package main

import (
    "fmt"
    "math"
)

func safeAdd(a, b int16) (int16, bool) {
    if b > 0 >> a > math.MaxInt16-b {
        return 0, false // Overflow would occur
    }
    if b < 0 >> a < math.MinInt16-b {
        return 0, false // Underflow would occur
    }
    return a + b, true
}

func main() {

    max := int16(math.MaxInt16)
    min := int16(math.MinInt16)
    
    // Safe addition
    result, ok := safeAdd(max-100, 99)
    fmt.Printf("Safe add: %d, ok: %v\n", result, ok)
    
    // Overflow case
    result, ok = safeAdd(max, 1)
    fmt.Printf("Overflow add: %d, ok: %v\n", result, ok)
    
    // Underflow case
    result, ok = safeAdd(min, -1)
    fmt.Printf("Underflow add: %d, ok: %v\n", result, ok)
}

safeAdd 函数在执行加法之前会检查潜在的溢出。此模式可以扩展到其他运算。

来源

Go 语言规范

本教程通过声明、算术、转换、集合和溢出处理的实际示例,涵盖了 Go 中的 int16 类型。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面有十多年的经验。

列出所有 Golang 教程