Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

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.

SyntaxWhere It Fits
var name stringZero-value declaration or explicit type.
var count = 10Declaration with inferred type.
count := 10Short local declaration inside a function.
var AppName = "Demo"Package-level variable.
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
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
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.

TypeZero ValueExample Meaning
int, float640No count or amount yet
stringEmpty stringNo text provided
boolfalseFlag is off
Pointer, slice, map, interfacenilNo value allocated
StructEach field gets its own zero valueA 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.

TypeCommon Use
stringNames, emails, slugs, messages
boolFeature flags and true/false state
intCounts, indexes, IDs in many local cases
float64Decimal measurements and calculations
[]byteRaw 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
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
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.

Key Takeaways
  • 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.

Ready to Level Up Your Skills?

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