Tutorials Logic, IN info@tutorialslogic.com

Golang Variables and Data Types: var, const, :=, string, int, bool

Declaring Variables

Golang gives you several declaration styles. Use var when you want an explicit type, a package-level variable, or a zero-value declaration. Use := for short local declarations inside functions.

A good rule is simple: if the type is obvious from the right side, let Golang infer it. If the zero value matters or the type is not obvious, write the type explicitly.

Syntax Where It Fits
var name string Zero-value declaration or explicit type.
var count = 10 Declaration with inferred type.
count := 10 Short local declaration inside a function.
var AppName = "Demo" Package-level variable.

Variable Declarations

Variable Declarations
package main

import "fmt"

var appName string = "Tutorials Logic"

func main() {
    var username string = "admin"
    var score int
    active := true

    score = 95
    fmt.Println(appName, username, score, active)
}

Short Declarations

The := syntax is only available inside functions. It declares at least one new variable and infers the type from the assigned value.

Short declarations are common in local code, especially for temporary values and result-plus-error patterns. They keep function bodies compact while preserving static typing.

Short Declaration

Short Declaration
func main() {
    course := "Golang"
    lessons := 18
    published := true

    fmt.Println(course, lessons, published)
}

Type Inference

Type inference means Golang can choose the variable type from the assigned value. For example, count := 10 becomes an int, and name := "Golang" becomes a string.

Inference keeps code concise, but it does not make Golang dynamically typed. Once a variable has a type, you cannot assign a value of a different type to it.

Inferred Types

Inferred Types
package main

import "fmt"

func main() {
    lessons := 16       // int
    course := "Golang"  // string
    published := true   // bool

    fmt.Printf("%T %T %T\n", lessons, course, published)
}

Zero Values

Variables declared without a value receive a zero value. This makes declarations predictable and lets you create usable values without manually initializing every field.

Zero values are useful, but they should still be read carefully. An empty string may be a valid value or it may mean missing data, depending on the business rule.

Type Zero Value Example Meaning
int, float64 0 No count or amount yet
string Empty string No text provided
bool false Flag is off
Pointer, slice, map, interface nil No value allocated
Struct Each field gets its own zero value A usable empty struct value

Basic Types

Golang has clear built-in types for text, numbers, booleans, bytes, runes, and complex numbers. In application code, the most common beginner types are string, bool, int, float64, and byte slices.

Choose types based on meaning. Use integers for counts and IDs, floating-point values for measurements that can have decimals, and strings for text. For money, many production systems avoid float values and use integer cents or a decimal library.

Type Common Use
string Names, emails, slugs, messages
bool Feature flags and true/false state
int Counts, indexes, IDs in many local cases
float64 Decimal measurements and calculations
[]byte Raw file, network, or encoded data

Constants

Constants use const and cannot be reassigned. Use constants for values that are part of a rule, configuration default, status label, or fixed calculation.

Constants are evaluated at compile time. They are excellent for names that make code easier to understand, such as tax rates, role names, default limits, and timeouts.

Constants - Bash Command

Constants - Bash Command
package main

import "fmt"

const maxLoginAttempts = 3
const defaultRole = "reader"

const (
    StatusDraft     = "draft"
    StatusPublished = "published"
)

func main() {
    fmt.Println(defaultRole, maxLoginAttempts, StatusDraft)
}

Explicit Type Conversion

Golang avoids many implicit conversions. If you combine an int with a float64, convert one side explicitly so the result is clear.

This can feel strict at first, but it prevents subtle production bugs caused by hidden conversions, rounding, or loss of precision.

Numeric Conversion

Numeric Conversion
package main

import "fmt"

func main() {
    quantity := 3
    price := 499.50
    total := float64(quantity) * price

    fmt.Printf("Total: %.2f\n", total)
}

Naming and Scope

Variable names should explain the value without becoming noisy. Short names like i and err are fine in small scopes. Longer-lived values deserve clearer names such as totalViews or currentUser.

Scope matters. Prefer declaring variables close to where they are used. Smaller scopes reduce accidental reuse and make functions easier to understand.

Before you move on

Golang Variables and Data Types: var, const, :=, string, int, bool Mastery Check

7 checks
  • Use := for short local declarations inside functions.
  • Use var for explicit types, package variables, and zero-value declarations.
  • Type inference keeps code concise while preserving static typing.
  • Zero values make variables predictable but still require business meaning.
  • Use const for values that should not change.
  • Golang prefers explicit conversions instead of hidden type coercion.
  • Declare variables close to where they are used.
Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.