본문 바로가기
Go

[Go] Basic

by llHoYall 2020. 10. 26.

Go is a statically typed language.

 

Let me show you a very default Go program.

package main

import "fmt"

func main() {
  fmt.Println("Hello, Go!")
}

The first line declares which package to use. We run the program directly in the terminal, so the main package is needed.

The next line imports fmt package.

The example program prints the message through Println function in the fmt package.

Then finally, it is the main function that a program starts.

 

If you execute this program, it prints the "Hello, Go!" string in the terminal.

※ You need to keep in mind these things.

- Every Go files have to start with package statement.
- All packages that is refered by Go files must be imported.
- Go can import packages that is only really used.
- Go program finds the main function first when it is executed.
- Go is case sensitive.

Comments

Single line comments use //, and block comments use /* and */.

// This is a single line comment.

/*
This is a block comment.
*/

Standard Input / Output

package main

import (
  "bufio"
  "fmt"
  "os"
)

func main() {
  fmt.Print("Enter user input: ")
  input, _ := bufio.NewReader(os.Stdin).ReadString('\n')
  fmt.Println(input)
}

When we want to write to standard output, we use Print or Println methods in the fmt package.

  • Print : without a newline
  • Prinln : with a newline

When we want to read from standard input, we use NewReader method in the bufio package with Stdin property in the os package.

Go Commands

Compile source code to a binary file

$ go build <pathspec>

Compile and Execute Program

A compiled executable file will not be saved.

$ go run <pathspec>

Install a built Executable File

$ go install <pathspec>

Align a Source Code using Formatter

$ go fmt

Run Test

$ go test
$ go test -cover

Download Packages

$ go get <url>

Show Package Documents

$ go doc <pathspec>
$ godoc

Access http://localhost:6060/ after running godoc command.

Show Current Version of Go

$ go version

'Go' 카테고리의 다른 글

[Go] Configure VSCode  (0) 2020.11.28
[Go] User-Defined Type  (0) 2020.11.02
[Go] Variable  (0) 2020.10.21
[Go] Data Types  (0) 2020.10.21
[Go] Getting Started (시작하기)  (0) 2020.08.28

댓글