Key Concepts

Review core concepts you need to learn to master this subject

Go Values

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

In Go, values can be unnamed or named. Unnamed values are literals such as 3.14, true, and "Codecademy". Named values have a name attached to the value and they can either be unchangeable as constants or changeable as variables once defined.

Go Data Types

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

In Go, values have a data type. The data type determines what type of information is being stored and how much space is needed to store it. Go has basic data types such as:

  • string
  • bool
  • numeric types:
    • int8, uint8, int16, uint16, int32 , uint32, int64, uint64, int, uint, uintptr
    • float32, float64
    • complex64, complex128

Go Variables

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

A Go variable has a name attached to a value but unlike a Go constant, a variable’s value can be changed after it has been defined. There are four ways to declare and assign a Go variable:

  • use the var keyword followed by a name and its data type. This variable can be assigned later in the program. For example:
    var fruit string string = "apple"
  • use the var keyword followed by a name, data type, = and value.
    var fruit string = "apple"
  • use the var keyword, followed by a name, = and value. Ignore the data type and let the compiler infer its type.
    var fruit = "apple"
  • skip the var keyword, define a name followed by := and value and let the compiler infer its type.
    fruit := "apple"

Go Errors

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

In Go, errors are raised when the compiler doesn’t recognize the code as valid. The error message is printed to the terminal and contains the following information:

  • The filename
  • The line that raises the error
  • The number of characters from the left side that raises the error
  • The type of error and reason for raising the error

For example:

./Main.go:11:3: undefined: dinner

This particular error occurs in the file main.go at line 11, 3 characters into the line, and its error type and reason is "undefined: dinner".

Go Strings

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

A Go string is a data type that stores text or a sequence of characters in any length in double-quoted form. To concatenate two strings, use the + operator.

Go Zero Values

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

In Go, when a variable is declared without initializing a value, it has a default value. The default value is known as the zero value.

Different zero values exist for different data types:

Type Zero Value ints 0 floats 0 string "" (empty string) boolean false

Go Inferred Int Type

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

When we declare a Go variable without specifying its data type and assign the variable (using := or var =) to a whole number, the Go compiler automatically infers the variable data type as an int. For example:

score := 85 var temperature = 60

Go Updating Variables

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

Unlike constants, Go variables can change their values if we reassign new values to them. For example:

var zipcode = "02134" zipcode = "03035"

Go supports additional assignment operators that updates a variable by performing an operation such as addition, subtraction, multiplication or division to iself.

// sum = sum + value sum += value // total = total - value total -= value // average = average / quantity average /= quantity // price = price * quantity price *= quantity

Go Multiple Variable Declaration

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

Multiple Go variables can be declared and initialized on the same line delimited with a comma. If they are of the same type, the type can be optionally declared after the variable names before the assignment operator. For example:

var x, y int = -1, 5 a, b := 7, 2 fmt.Println(x, y, a, b) // -1, 5, 7, 2

If the variables are of different types, they can also be declared on the same line without the type designation.

found, answer := true, "yes" var name, age = "Steve", 35 fmt.Println(found, answer, name, age) // true, "yes", "Steve", 35

Go Fmt .Print() and .Println()

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

The Go fmt package supports two closely-related functions for formatting a string to be displayed on the terminal. .Print() accepts strings as arguments and concatenates them without any spacing. .Println(), on the other hand, adds a space between strings and appends a new line to the concatenated output string.

fmt.Print("I", "am", "cool") // Iamcool fmt.Println("I", "am", "cool") // I am cool

Go Fmt .Printf() Function

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

The Go .Printf() function in fmt provides custom formatting of a string using one or more verbs. A verb is a placeholder for a named value (constant or variable) to be formatted according to these conventions:

  • %v represents the named value in its default format
  • %d expects the named value to be an integer type
  • %f expects the named value to be a float type
  • %T represents the type for the named value

The first argument for .Printf() is the string with verb(s) followed by one or more named values corresponding to the verb(s). Unlike .Println(), .Printf() does not append a newline to the formatted string.

Go Fmt .Scan() Function

// literal unnamed value fmt.Println("PI = ", 3.14159) // constant named value const pi = 3.14159 // variable named value var radius = 6

The Go fmt .Scan() function scans user input from the terminal and extracts text delimited by spaces into successive arguments. A newline is considered a space. This function expects an address of each argument to be passed.

package main import "fmt" func main() { var name string var age int fmt.Println("What's your name and age?") fmt.Scan(&name, &age) fmt.Printf("You entered %v and %d.\n", name, age) }

A session on the terminal may look like this:

$ What's your name and age? $ Marcia 32 $ You entered Marcia and 32.
Arrow Chevron Left Icon
Learn Go: Variables and Types
Lesson 1 of 2
Arrow Chevron Right Icon
  1. 1
    Programs, like the ones we write in Go, are excellent at processing and performing operations on data. But in programming, “data” can be so many different things. Data can be numbers, boolean value…
  2. 2
    In Go, values can be many things. Just to name a few, values can be numbers (like 109), or text wrapped in quotes (like “Hello world”). These values can be written into code as is, and are called _…
  3. 3
    In addition to literal (aka unnamed) values, there are also named values. Naming a value in Go means creating a word that will represent that value. One example of named values are constants,…
  4. 4
    Programming languages need to process and organize data. That data is stored as binary numbers (numbers consisting of 0’s and 1’s) in the memory of your computer. In this way, binary numbers are us…
  5. 5
    Go has 15 different numeric types that fall into the three categories: int, float, and complex. That means there are fifteen different ways to describe a number in Go. This includes 11 different in…
  6. 6
    Now that we have some background on what types are, we can talk about what variables are and how we make and use them. A variable is a named value (like a constant) with the added feature that it c…
  7. 7
    There is no shame in having your code fail to run. Programming errors and exceptions happen all the time and learning to read and understand them is an indispensable tool in a programmer’s toolbox….
  8. 8
    Variables are placeholder names that we use to refer to values that we intend to update over the course of our program. Updating our variable is also called assigning a value to a variable. In or…
  9. 9
    We’ve talked about numeric types so far, but Go offers a few other built-in types. One particularly useful type is called a string. A string is Go’s type for storing and processing text. In a gen…
  10. 10
    Even before we assign anything to our variables they hold a value. Go’s designers attempted to make these “sensible defaults” that we can anticipate based on the variable’s types. All numeric varia…
  11. 11
    There is a way to declare a variable without explicitly stating its type using the short declaration := operator. We might use the := operator if we know what value we want our variable to store wh…
  12. 12
    There is one more common way to define an int in Go. Computers actually have a default length for the data in their Read-Only Memory (ROM). Some newer comps may have more processing power and can s…
  13. 13
    Variables are different from constants because we can update them. This update feature becomes incredibly important when we need to use the original value of a variable for a calculation (or any ge…
  14. 14
    So far we’ve been declaring variables one by one, each on their own separate line. But Go actually allows us to declare multiple variables on a single line, in fact, there’s a few different syntaxe…
  15. 15
    In this lesson you learned: How to use literals in a Go program. How to create constants that give names to values. The basic types in Go: ints, floats, complexs, and strings. The different…
  1. 1
    fmt is one of Go’s core packages. We’ve used it for print information to the terminal using the method fmt.Println(). fmt has a broader purpose, helping us format data, which is why it’s sometime…
  2. 2
    fmt.Println() allows us to print to the terminal and view the data that we’re working with. It has some defaulting styling built-in that makes viewing data easier for us. fmt.Println() prints its _…
  3. 3
    Using fmt.Println() and fmt.Print() we have the ability to concatenate strings, i.e. combine different strings into a single string: guess := “C” fmt.Println(“Is”, guess, “your final answer?”) //…
  4. 4
    In addition to %v, Go has a variety of useful verbs (check their documentation for a comprehensive list). Let’s go over a few in this exercise, starting …
  5. 5
    While we’ve been using fmt methods to print things out, remember, it’s the formatter package. We have other methods that don’t print strings, but format them instead like fmt.Sprint() and fmt.Sprin…
  6. 6
    If we need to interpolate a string, without printing it, then we can use fmt.Sprintf(). Just like fmt.Printf(), fmt.Sprintf() can also use verbs: correctAns := “A” answer := fmt.Sprintf(“And the…
  7. 7
    Another helpful method from the fmt package is .Scan() which allows us to get user input! Let’s see an example of this in action: fmt.Println(“How are you doing?”) var response string fmt.Scan(…
  8. 8
    Wonderful work getting through the fmt package’s methods! There are many more methods that we didn’t include, but you can read through Go’s fmt documentation for more…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo