首頁 >後端開發 >Golang >可以在 Go 中的單一結構體欄位中儲存不同的資料類型嗎?

可以在 Go 中的單一結構體欄位中儲存不同的資料類型嗎?

Patricia Arquette
Patricia Arquette原創
2024-11-15 16:27:03885瀏覽

Can You Store Different Data Types in a Single Struct Field in Go?

Declaring and Using Struct Fields for Multiple Data Types in Go

In Go, you can define a struct to represent related data. However, what if you want a struct field to be able to store both string and int values?

To understand this issue better, consider the following struct:

type testCase struct {
   input   string
   isValid bool
}

This struct is designed to store a test case where input is a string and isValid is a boolean. In some scenarios, you may want to allow input to be either a string or an int.

Initially, you might consider converting the int input to a string and back to int while processing. However, this approach is inefficient and error-prone.

Another option could be defining two separate structs, such as testCaseInt and testCaseStruct. This would solve the problem, but it leads to unnecessary code duplication.

Is it possible to store different data types in a single struct field using an interface?

No, it's not possible in Go versions prior to 1.18. Go's type system does not support sum types, which are types that can represent multiple variants of data.

In Go 1.18, sum types will be supported through the introduction of generics. However, until then, there is no built-in way to achieve this functionality.

以上是可以在 Go 中的單一結構體欄位中儲存不同的資料類型嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn