Data Types

Go has several basic types including numerics, strings, booleans, arrays, slices, and maps. Let's explore each type in detail.

1. Numeric Types

Integer Types

  1. Signed integers

    • int8: -128 to 127

    • int16: -32768 to 32767

    • int32: -2147483648 to 2147483647

    • int64: -9223372036854775808 to 9223372036854775807

    • int: Platform dependent (32 or 64 bit)

  2. Unsigned integers

    • uint8: 0 to 255 (byte is an alias for uint8)

    • uint16: 0 to 65535

    • uint32: 0 to 4294967295

    • uint64: 0 to 18446744073709551615

    • uint: Platform dependent (32 or 64 bit)

    • uintptr: Integer large enough to store any pointer address

Floating-Point Types

  • float32: IEEE-754 32-bit floating-point numbers

  • float64: IEEE-754 64-bit floating-point numbers (default for floating-point)

Complex Numbers

  • complex64: Complex numbers with float32 real and imaginary parts

  • complex128: Complex numbers with float64 real and imaginary parts (default for complex)

Floating-Point Formatting

Examples

2. Boolean Type

The boolean type bool represents two possible values: true and false.

3. String Type

Strings in Go are immutable sequences of bytes. This means once a string is created, it cannot be modified.

String Immutability

String Performance Considerations

4. Array Type

Arrays in Go have a fixed length and contain elements of the same type.

5. Slice Type

Slices are dynamic, flexible views into arrays. Understanding their behavior when copying is crucial.

Slice Behavior and Sharing

Slice Capacity Behavior

6. Map Type

Maps in Go are reference types, which affects their copying behavior.

Map Reference Behavior

Map Concurrency

7. Struct Type

Structs are value types, but can contain reference type fields.

Struct Copy Behavior

8. Interface Type

Interfaces define behavior by declaring a set of methods.

Best Practices for Data Type Usage

  1. String Handling

    • Use strings.Builder for string concatenation in loops

    • Use bytes.Buffer when working with I/O

    • Consider using []byte for heavy string manipulation

  2. Slice Management

    • Pre-allocate slices when size is known

    • Use copy() for slice copying

    • Be careful with slice references in long-lived objects

  3. Map Usage

    • Use make() to initialize maps

    • Check for existence using two-value assignment

    • Use sync.Map for concurrent access

  4. Memory Efficiency

    • Release references to large slices or maps when no longer needed

    • Use pointer receivers for large structs

    • Consider using sync.Pool for frequently allocated objects

  5. Type Conversion

    • Always check for overflow when converting between numeric types

    • Use strconv package for string conversions

    • Handle errors in string-to-number conversions

Additional Resources

Last updated

Was this helpful?