Home > Backend Development > Golang > How Can I Get the Size of Any Data Structure in Go?

How Can I Get the Size of Any Data Structure in Go?

Mary-Kate Olsen
Release: 2024-12-01 13:13:11
Original
723 people have browsed it

How Can I Get the Size of Any Data Structure in Go?

Generic Function for Determining Data Structure Size in Go

In Go, the lack of a native function similar to C's sizeof operator poses a challenge when retrieving the size of arbitrary data structures. To overcome this, leveraging interfaces and reflection offers a solution.

The provided code attempts to achieve this using:

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func main() {
    type myType struct {
        a int
        b int64
        c float32
        d float64
        e float64
    }
    info := myType{1, 2, 3.0, 4.0, 5.0}
    getSize(info)
}

func getSize(T interface{}) {
    v := reflect.ValueOf(T)
    const size = unsafe.Sizeof(v)
    fmt.Println(size) // Incorrectly produces 12
}
Copy after login

However, this approach yields an incorrect result as it calculates the size of the reflect.Value structure rather than the object stored in the interface T.

The solution lies in utilizing the Size() method of the reflect.Type:

size := reflect.TypeOf(T).Size() // Corrects the size calculation
Copy after login

This modification enables the function to accurately determine the size of the input data structure, accounting for padding. In the example given, it correctly reports the size as 40.

The above is the detailed content of How Can I Get the Size of Any Data Structure in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template