[For self-learning] Go2 for the first time

Looking back on basic grammar

main package

When you compile and execute the program, the main () function in the main package is executed first.

package main

func main() {


You can access the imported package with a dot in the package name.

package main

import (
func main() {
    fmt.Println("hello world")

Specifying options

Can be used with f if an arbitrary name (f in the above) is specified. If _ is added, it means not to use. If you add., You can omit the package name when using it.

package main

import (
    f "fmt"
    _ "github.com/wdpress/gosample"
    . "strings"

func main() {
    // fmt.Println()Is f.Println()become
    // strings.ToUpper()Is To Upper()Has become
    f.Println(ToUpper("hello world"))


//var message string = "hello world"
//var foo, bar, buz string = "foo", "bar", "buz"

func main() {
    //Both writings have the same meaning
    // var message string = "hello world"
    message := "hello world"

    const Hello string = "hello"
    Hello = "bye" // cannot assign to Hello

Variable declaration is from var. Similar to JS. It's similar in that you can make multiple declarations. The var and variable types are optional. The type is inference. It doesn't have to be similar here ...


func main() {
    a, b := 10, 100
    if a > b {
        fmt.Println("a is larger than b")
    } else if a < b {
        fmt.Println("a is smaller than b")
    } else {
        fmt.Println("a equals b")

if n == 10
    //This is an error
n == 10 ? fmt.Println(n): fmt.Println(0)
//This is also an error

You don't need parentheses in if. I personally want it. Omitting curly braces is an error. Omission of if is also an error. : thumbsup:


func main() {
    for i := 0; i < 10; i++ {
    for {  //infinite loop

For also does not require parentheses. There is no while.


func main() {
    n := 3
    switch n {
    case 3:
        n = n - 1
    case 2:
        n = n - 1
    case 1:
        n = n - 1
        fmt.Println(n) // 0

There is no need to write a break because the go switch exits when the case is over. If you want to continue, fall through.


func sum(i, j int) { // func sum(i int, j int)Same as
    fmt.Println(i + j)

If the argument types are the same, they can be grouped together at the end.

func swap(i, j int) (int, int) {
    return j, i

func main() {
    x, y := 3, 4
    x, y = swap(x, y)
    fmt.Println(x, y) // 4, 3

    x = swap(x, y) //Compile error

    x, _ = swap(x, y) //Ignore the second return value
    fmt.Println(x) // 3

    swap(x, y) //Can be compiled and executed

The function can return multiple values. If there is no return value, it will be a compile error You can explicitly ignore it with _.

Function that returns an error

func main() {
    file, err := os.Open("hello.go")
    if err != nil {
        //Error handling
        //Exit processing to another location with return etc.
    //Processing using file

If not an error, nil. Use the errors package for your own errors. There is a convention to put the error last, so your own API will follow suit.

package main

import (

func div(i, j int) (int, error) {
    if j == 0 {
        //Returns a self-made error
        return 0, errors.New("divied by zero")
    return i / j, nil

func main() {
    n, err := div(10, 0)
    if err != nil {
        //Output an error and exit the program

Named return value

func div(i, j int) (result int, err error) {
    if j == 0 {
        err = errors.New("divied by zero")
        return // return 0,Same as err
    result = i / j
    return // return result,Same as nil

You can name the return value and treat it as a variable initialized with a zero value. In this case, it is not necessary to specify the value to be returned after return.

Function literal

You can create anonymous functions. To create a function to execute immediately:

func main() {
    func(i, j int) {
        fmt.Println(i + j)
    }(2, 4)

Functions can be assigned to variables. This is also the same as JS.

var sum func(i, j int) = func(i, j int) {
    fmt.Println(i + j)

func main() {
    sum(2, 4)


The go array has a fixed length. When passing an array to a function, it is passed by value.

func fn(arr [4]string) {
    arr[0] = "x"
    fmt.Println(arr) // [x b c d]

func main() {
    arr := [4]string{"a", "b", "c", "d"}
    fmt.Println(arr) // [a b c d]


Slice = variable length array. If you use range in a for statement, you can get both the subscript and the value.

s1 := []string{"a", "b"}
s2 := []string{"c", "d"}
s1 = append(s1, s2...) //Add s2 to s1
fmt.Println(s1)        // [a b c d]

var arr [4]string

arr[0] = "a"
arr[1] = "b"
arr[2] = "c"
arr[3] = "d"

for i, s := range arr {
    // i =Subscript, s =value
    fmt.Println(i, s)

If you specify the start point and end point with a colon between them, you can cut out the values ​​in that range. If the start point and end point are omitted, they will be the beginning and end, respectively.

s := []int{0, 1, 2, 3, 4, 5}
fmt.Println(s[2:4])      // [2 3]
fmt.Println(s[0:len(s)]) // [0 1 2 3 4 5]
fmt.Println(s[:3])       // [0 1 2]
fmt.Println(s[3:])       // [3 4 5]
fmt.Println(s[:])        // [0 1 2 3 4 5]


//var month map[int]string = map[int]string{}

month := map[int]string{
    1: "January",
    2: "February",
fmt.Println(month) // map[1:January 2:February]

To retrieve the key from the map. If you want to check if there is a key, you can judge by the second argument. (Returned with bool)

jan := month[1]
fmt.Println(jan) // January

_, ok := month[1]
if ok {
    //If there is data

Like slices, range can be used.


When performing file operations, it is necessary to close the used file. If there is a possibility that it will not be closed due to disconnection on the way, add defer. In the following, it will always be executed just before exiting main ().

func main() {
    file, err := os.Open("./error.go")
    if err != nil {
        //Error handling
    //Always executed before exiting the function
    defer file.Close()
    //Normal processing


An error that cannot be expressed by the return value is generated by a method called panic.

func main() {
    defer func() {
        err := recover()
        if err != nil {
            // runtime error: index out of range

    a := []int{1, 2, 3}
    fmt.Println(a[10]) //Panic occurs

The error that occurs in this panic can be acquired by a built-in function called recover (), and error processing can be performed there. By writing recover () in defer, it is possible to handle the error that occurred in the panic and then exit the function.

Panic can also be generated by yourself using the built-in function panic ().

a := []int{1, 2, 3}
for i := 0; i < 10; i++ {
    if i >= len(a) {
        panic(errors.New("index out of range"))

However, panic is used when the error cannot be expressed as a return value, a system error that cannot be recovered, or when a global escape is unavoidable. The basic is expressed by the return value.

Recommended Posts

[For self-learning] Go2 for the first time
Kaggle for the first time (kaggle ①)
Kaguru for the first time
See python for the first time
Start Django for the first time
I tried tensorflow for the first time
MongoDB for the first time in Python
Let's try Linux for the first time
I tried using scrapy for the first time
[Note] Deploying Azure Functions for the first time
I tried python programming for the first time.
I tried Mind Meld for the first time
Try posting to Qiita for the first time
What I got into Python for the first time
I tried Python on Mac for the first time.
Register a task in cron for the first time
For the first time, I learned about Unix (Linux).
AI Gaming I tried it for the first time
Summary of stumbling blocks in Django for the first time
Introducing yourself at Qiita for the first time (test post)
I tried the Google Cloud Vision API for the first time
If you're learning Linux for the first time, do this!
Differences C # engineers felt when learning python for the first time
Java programmer tried to touch Go language (for the time being)
First time python
I tried logistic regression analysis for the first time using Titanic data
Impressions and memorandums when working with VS code for the first time
For the first time in Numpy, I will update it from time to time
A useful note when using Python for the first time in a while
Since I'm free, the front-end engineer tried Python (v3.7.5) for the first time.
For the time being, import them into jupyter
Make a histogram for the time being (matplotlib)
Use logger with Python for the time being
Run yolov4 "for the time being" on windows
I played with Floydhub for the time being
Try using LINE Notify for the time being
virtualenv For the time being, this is all!
Looking back on the machine learning competition that I worked on for the first time
Let's display a simple template that is ideal for Django for the first time
GTUG Girls + PyLadiesTokyo Meetup I went to machine learning for the first time
Import audit.log into Splunk and check the behavior when Splunk is started for the first time
The first GOLD "JDBC"
Molecular dynamics simulation to try for the time being
After attending school, I participated in SIGNATE's BEGINNER limited competition for the first time.
The first GOLD "Function"
I want to create a lunch database [EP1] Django study for the first time
I want to create a lunch database [EP1-4] Django study for the first time
I will install Arch Linux for the time being.
Next to Excel, for the time being, jupyter notebook
Introduction to Deep Learning for the first time (Chainer) Japanese character recognition Chapter 1 [Environment construction]
What is a dog? Django--Getting Started with Form for the First Time POST Transmission Volume
What kind of environment should people who are learning Python for the first time build?
I want to move selenium for the time being [for mac]
I tried running PIFuHD on Windows for the time being
[Understand in the shortest time] Python basics for data analysis
To write a test in Go, first design the interface
[Introduction to Reinforcement Learning] Reinforcement learning to try moving for the time being
For the time being, try using the docomo chat dialogue API
I want to create a Dockerfile for the time being.
Code that I wish I had remembered when I participated in AtCoder for the first time (Reflection 1 for the next time)
The story of releasing a Python text check tool on GitHub x CircleCI for the first time