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

What are the different types of data types in Go?

1个答案

1

In Go, data types fall into several main categories:

1. Basic Types

Basic types include:

  • Integer types (int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64)
  • Floating-point types (float32, float64)
  • Complex types (complex64, complex128)
  • Boolean types (bool)
  • String types (string)

2. Composite Types

Composite types enable combining basic data types into more complex structures:

  • Arrays: Fixed-length, for example, var a [10]int
  • Slices: Dynamic-length, allowing elements to be added dynamically, for example, var s []int
  • Structs (struct): Can contain multiple data types of different kinds, for example:
go
type Person struct { Name string Age int }
  • Pointers (pointer): Point to a memory address, for example, var p *int
  • Functions: Can be assigned to variables and passed as parameters, for example:
go
func add(x, y int) int { return x + y }
  • Interfaces (interface): Define a set of method signatures, for example:
go
type Shape interface { Area() float64 Perimeter() float64 }
  • Maps: Key-value collections, for example, map[string]int
  • Channels (channel): Used for passing data between different Goroutines, for example, ch := make(chan int)

3. Type Aliases and Custom Types

You can create new type names to represent existing data types, for example:

go
type UserID int

This allows you to provide more descriptive names for basic data types, enhancing code readability and maintainability.

Example

A simple example using these data types could be a program managing library books:

go
type Book struct { Title string Author string Pages int } func main() { var myBook Book myBook.Title = "Learning Go" myBook.Author = "John Doe" myBook.Pages = 300 fmt.Println("Book:", myBook.Title, "by", myBook.Author) }

In this example, we define a struct Book that contains several different basic data types, then create a Book type variable in the main function and output relevant information. This demonstrates how to use different data types in Go to build practical applications.

2024年7月20日 03:19 回复

你的答案