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 (
"fmt"
"github.com/wdpress/gosample"
"strings"
)
func main() {
fmt.Println("hello world")
}
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"
fmt.Println(message)
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 ...
if
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
fmt.Println(n)
//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:
for
func main() {
for i := 0; i < 10; i++ {
fmt.Println(i)
}
for { //infinite loop
doSomething()
}
}
For also does not require parentheses. There is no while.
switch
func main() {
n := 3
switch n {
case 3:
n = n - 1
fallthrough
case 2:
n = n - 1
fallthrough
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 _.
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 (
"errors"
"fmt"
"log"
)
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
log.Fatal(err)
}
fmt.Println(n)
}
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.
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"}
fn(arr)
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.
defer
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
log.Fatal(err)
}
}()
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"))
}
fmt.Println(a[i])
}
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.