乐闻世界logo
搜索文章和话题

How can we declaration mixed variable in Go?

1个答案

1

In Go, variables that can hold multiple types typically refer to variables capable of storing values of different types. Go provides several ways to declare such variables:

  1. Using structs: This is a common method for handling different data types. You can define a struct to hold fields of various types.
go
type Person struct { Name string Age int GPA float64 }

Here, the Person struct contains a string-typed Name, an int-typed Age, and a float64-typed GPA.

  1. Using interfaces: Interfaces can be used to handle different types, especially when you are unsure of the data type. The interface{} can store values of any type.
go
var mixVariable interface{} mixVariable = 20 // int mixVariable = "Hello" // string mixVariable = 99.99 // float64

Here, mixVariable can store values of any type.

  1. Using multiple assignment: In Go, you can declare and initialize multiple variables of different types simultaneously.
go
var ( name string = "Alice" age int = 30 weight float64 = 65.5 )

In practical applications, the choice depends on the specific scenario. For example, if you are handling a person's data, using a struct is appropriate. If you need a variable that can store any type of data, you can use interface{}. If you simply need to declare several variables of different types, use multiple assignment.

2024年8月7日 18:13 回复

你的答案