go语言对结构体数组求长度


go语言别用那个sizeof去求 求出来的好像不对 要用len函数

// getting the length of an array is silly, because the length is part of the array's static type

myArray := [3]int{1, 2, 3}

fmt.Println(len(myArray)) // prints 3

// getting the length of a slice

mySlice := []int{1, 2, 3}

fmt.Println(len(mySlice)) // prints 3

示例

package main

import (
    "fmt"
)

type Man struct {
    Name string
    Age  int
}

func main() {
    var m []Man = []Man{{Name: "John", Age: 20}, Man{Name: "Johnh", Age: 21}}
    fmt.Println(len(m))

}

运行结果

PS C:\Users\Administrator\Desktop\go2> go run .\main.go
2

声明:小小博客|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - go语言对结构体数组求长度


Carpe Diem and Do what I like