Welcome to our deep dive into Go, a powerful and modern programming language known for its simplicity and efficiency. In this lesson, we'll explore the concept of Go's underlying type system, shedding light on why it's such a game-changer in the world of development.
š” Pro Tip: Go, also known as Golang, was developed by Google and is widely used in building scalable and high-performance systems.
In Go, every variable has a type. Types define the kind of data a variable can hold and the operations that can be performed on it. Let's take a look at the basic types in Go:
Integer Types:
int8, int16, int32, int64: Signed integers of varying sizes.uint8, uint16, uint32, uint64: Unsigned integers of varying sizes.int: An alias for int32.uint: An alias for uint32.byte: An alias for uint8.Floating Point Types:
float32: Single precision floating-point numbers.float64: Double precision floating-point numbers.Boolean Type:
bool: Represents either true or false.String Type:
string: Represents a sequence of bytes.Complex Number Types:
complex64: Complex numbers using float32 for real and imaginary parts.complex128: Complex numbers using float64 for real and imaginary parts.In Go, you declare and assign values to variables at the same time. Here's an example:
package main
import "fmt"
func main() {
var a int = 10
var b float64 = 20.5
var c string = "Hello, World!"
fmt.Println("Integer:", a)
fmt.Println("Float:", b)
fmt.Println("String:", c)
}š Note: In the above example, we've declared and initialized three variables: a, b, and c. The fmt.Println() function is used to print the values of these variables.
Go allows you to convert one data type to another. Here's an example:
package main
import "fmt"
func main() {
var a int = 10
var b float64 = float64(a)
fmt.Println("Integer:", a)
fmt.Println("Float:", b)
}š” Pro Tip: Always ensure that the destination type can hold the value of the source type during conversion.
Go supports type inference, meaning the type of a variable is inferred from the initial value you assign to it. Here's an example:
package main
import "fmt"
func main() {
a := 10
b := 20.5
c := "Hello, World!"
fmt.Println("Integer:", a)
fmt.Println("Float:", b)
fmt.Println("String:", c)
}In this example, Go infers the types of variables a, b, and c from the initial values.
What is the output of the following Go code?