Skip to content

wickertongue/learning_go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

Tutorials

Extras

Useful Links

Learnings

Creating Modules

Before writing any code, if you are writing a module you need to create the directory which will host your module.

Run the go mod init command, giving it your module path -- here, use example.com/greetings. If you publish a module, this must be a path from which your module can be downloaded by Go tools. That would be your code's repository.

go mod init example.com/name_of_module

Creating Applications

You go through the same motions as creating modules, and then declare a main package. In Go, code executed as an application must be in a main package.

package main

import (
  // packages
)

func main() {
    // do something using packages
}

Creating variables

In Go, the := operator is a shortcut for declaring and initializing a variable in one line (Go uses the value on the right to determine the variable's type). Taking the long way, you might have written this as:

var message string
message = fmt.Sprintf("Hi, %v. Welcome!", name)

Creating Functions

In Go, a function whose name starts with a capital letter can be called by a function not in the same package. This is known in Go as an exported name.

Creating Arrays

Slices

Go has something called slices. These are like arrays, except their sizes change dynamically in line with their contents.

When declaring a slice, you omit its size in the brackets, like this:

[]string.

This tells Go that the size of the array underlying the slice can be dynamically changed.

Creating Maps

In Go, you initialize a map with the following syntax: make(map[key-type]value-type)

make(map[string]int)

Values can be added to the map, using either map literals:

// this also creates the map

commits := map[string]int{
    "rsc": 3711,
    "r":   2138,
    "gri": 1908,
    "adg": 912,
}

Or separate statements:

m = make(map[string]int)
m["route"] = 66

Loops

For Loops

for _, name := range names {
  message, err := Hello(name)
  if err != nil {
    return nil, err
  }
  // In the map, associate the retrieved message with
  // the name.
  messages[name] = message
}

The range returns two values: the index of the current item in the loop and a copy of the item's value. You don't need the index, so you use the Go blank identifier (an underscore) to ignore it.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages