In this article let us learn about Basic Data Types in Go Language, Static Typing
With a syntax similar to C language, Go language is a statically-typed, compiled programming language that prioritizes dependability, performance, and simplicity. Go requires an understanding of data types since they define operations, classify items, and decide storage.
Static Typing in Go
Given that Go is a statically-typed language, variables in the language always have a fixed type that cannot be changed once defined. This is not like dynamically-typed languages, where the type of a variable might change as it is being executed. Even while static typing may appear laborious at first, it aids with program behaviour reasoning and identifies a broad range of typical errors during compilation.
Go offers type inference, which enables the compiler to determine the type of a variable from the value assigned, particularly when using the abbreviated declaration operator :=. As an illustration:
package main
import "fmt"
func main() {
// Type inferred as string
message := "Hello, Go!"
fmt.Println(message)
// Type inferred as int
number := 123
fmt.Println(number)
}
Output
Hello, Go!
123
Go assigns a “zero value” for each variable’s type when it is defined but not explicitly initialized. Strings, for example, default to “” (an empty text), booleans to false, pointers to nil, and integers to 0. This guarantees that, in contrast to certain other languages, there are no “undefined” values.
Basic Data Types
There are several pre-installed primitive kinds in Go.
Numbers
Go mostly distinguishes between floating-point and integer numbers.
Integers: These are positive, negative, and zero values that are whole integers devoid of a decimal place. The base-2 binary system is used by computers to represent numbers, and each type of integer has a specific size.
- There are many architecture-independent integer types with different bit sizes available in Go.
- For unsigned integers (which are positive or zero), use uint8, uint16, uint32, and uint64; for signed integers (which are positive and negative values), use int8, int16, int32, and int64.
- Additionally, there exist machine-dependent kinds.
- PTR, int, and uint. For integers, the int type is often chosen unless a certain size is needed.
- An integer may “wrap around” at runtime or result in a compile-time overflow error if its value is greater than the range of its type (if the compiler can discover it).
Floating-Point Numbers: These are actual numbers that have a decimal part.
- Float32 (single precision) and Float64 (double precision) are features of Go. Because float64 is more precise, it is usually advised.
- Inaccurate floating-point values might result in minor rounding mistakes since sometimes it’s hard to represent a number exactly.
- Complex64 and complex128 are also included in Go for complex numbers.
Aliases: For popular numeric types, Go has two handy aliases:
byte
: When working with raw binary data or character string components, this alias for uint8 is frequently used to make things plain.rune
: A Unicode code point, which might be a single character from any language, is represented by an alias for int32.
Strings
- When used to represent text, a string is a collection of one or more characters, such as letters, numbers, or symbols.
- Because Go strings are made up of individual bytes and support UTF-8 by default, multi-byte characters—like Chinese characters—are handled appropriately.
- Once a string is generated, its content cannot be altered.
- You can build string literals by using:
- Double quotes
""
: You can use specific escape sequences (such \n for newline and \t for tab), but you can’t use actual newlines. - Backticks ` (raw string literals): For multi-line text or pathways, they are helpful since they may span many lines and do not parse escape sequences.
- Double quotes
- Common string operations consist of:
- Finding length:
len("Hello")
. - Accessing individual characters by index (starting at 0):
"Hello"
. - Applying the + operator to concatenate
- “Hello” + “World” . Go deduces the meaning depending on the kinds of arguments, whereas + concatenates strings and adds integers. A string and a number cannot be concatenated directly without first converting the number to a string.
- Finding length:
Example
package main
import "fmt"
import "strconv" // For string conversions
func main() {
// String literal with double quotes and escape sequence
greeting := "Hello,\nWorld!"
fmt.Println("Double-quoted string:\n" + greeting)
// Raw string literal with backticks
rawString := `This is a
multi-line raw string. It ignores \n and \t.`
fmt.Println("\nRaw string:\n" + rawString)
// String operations
text := "Go Programming"
fmt.Printf("\nString operations:\n")
fmt.Printf("Length of \"%s\": %d\n", text, len(text)) // Length
fmt.Printf("Second character (byte value): %d\n", text[75]) // Indexing
fmt.Printf("Concatenation: %s\n", "Welcome to " + text) // Concatenation
// Concatenating string and number (requires conversion)
version := 1.21
messageWithVersion := "Go version " + strconv.FormatFloat(version, 'f', -1, 64)
fmt.Println(messageWithVersion) // Correct way to combine
}
Output
Double-quoted string:
Hello,
World!
Raw string:
This is a
multi-line raw string. It ignores \n and \t.
String operations:
Length of "Go Programming": 14
panic: runtime error: index out of range [75] with length 14
goroutine 1 [running]:
main.main()
/home/main.go:20 +0x175
Booleans
True or false is represented by a unique 1-bit integer type called a boolean value (bool).
- Booleans are employed in programs for logical differentiation and decision-making.
- They work in conjunction with logical operators:
&&
(AND):true && false
evaluates tofalse
.||
(OR):true || false
evaluates totrue
.!
(NOT):!true
evaluates tofalse
.
Example
package main
import "fmt"
func main() {
isLearning := true
isFun := false
fmt.Println("\nBoolean Examples:")
fmt.Printf("Is learning AND is fun? %t\n", isLearning && isFun)
fmt.Printf("Is learning OR is fun? %t\n", isLearning || isFun)
fmt.Printf("NOT isLearning? %t\n", !isLearning)
}
Output
Boolean Examples:
Is learning AND is fun? false
Is learning OR is fun? true
NOT isLearning? false
Composite Data Types
Go enables you to construct more intricate composite kinds by combining primitive types.
Arrays
A fixed-length, ordered series of items of the same type is called an array.
- The type of the array includes the length.
- The index for elements begins at 0.
- Arrays are copied when they are provided to functions or allocated to new variables.