Skip to content
Variables and Types
step 1/5

Reading — step 1 of 5

Learn

~3 min readGetting Started

Variables and Types

Go is statically typed — every variable has one type, fixed at compile time — but it rarely makes you say the type. The result reads like a scripting language and breaks like a compiled one: at build time, before your users see it.

Two ways to declare

go

The := form is what you'll use 95% of the time. Two rules keep it honest:

  • It declares — use it the first time only. Re-assigning uses plain =. (x := 1 then x := 2 in the same scope is a compile error; x = 2 is right.)
  • It only works inside functions. Package-level variables need var.

Everything unused is, as always in Go, a compile error — declare it, use it, or delete it.

Zero values: no such thing as uninitialized

Declare a variable without a value and Go doesn't leave garbage in it — every type has a defined zero value:

go

This is a real design decision with real consequences: there is no "uninitialized variable" bug class in Go, and idiomatic APIs are designed so the zero value is immediately useful (a zero bytes.Buffer or sync.Mutex works without setup).

The types you'll live in

  • int — the workhorse integer (64-bit on every machine you'll meet). Sized variants (int8int64, uint…) exist for file formats and protocols; default to int otherwise.
  • float64 — the default floating type; math functions speak it.
  • string, bool — as expected.

The rule that makes Go feel strict — and prevents a whole genre of bugs: no implicit conversions. Ever.

go

If two numbers mix, you wrote the conversion, and code reviewers can see exactly where precision changes. (Even int and int64 don't mix silently.)

Constants

go

Constants are compile-time values — they can't change, can't be computed at runtime, and (a pleasant Go quirk) numeric constants are untyped until used, so Pi works in float64 and float32 expressions alike without casting.

Reading input

Your exercise reads numbers from standard input. The simplest tool:

go

Those &s hand Scan the variables' addresses so it can fill them — pointers, properly explained in chapter 6; for now the pattern to memorize is Scan needs &. It skips spaces and newlines on its own, which is exactly right for grader-style input.

Naming, while we're here: Go style is camelCase for locals (maxValue), CapitalCase for exported names, and short names in short scopesi in a three-line loop is good Go; theLoopIndexVariable is not. gofmt fixes your spacing; taste fixes your names.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…