Basic syntax of the Go language
Here is a summary of the basic syntax for Go, a simple and fast programming language. I like the fast compile speed and the capability to generate single binaries. I made this for reference in case you need to remember. The following site are useful.
1.Packages
When a file is in a directory, the directory name is written at the beginning of the code. Example: foo folder
package foo
2.Entry Point
Programs start running in package main.
package main
func main(){
}
3.Comment
Comments not related to processing can be written in the following two ways.
// Comment
/*
multi-line
*/
4.Imports
Declare when to use the package.
Example: Case with fmt package
//One package
import "fmt"
//Multiple packages
import (
"fmt"
"string"
)
5.Variables
1.Explicit Definitions
Basic syntax: var name type
Can be assigned by variable_name=value.
var x,y,z int
x,y,z=1,2,3
2.Define several different types together
var(
x,y int
id string
)
3.Short variable declarations
i:=5
6.Basic types
1.Bool
var a bool
b:=false
2.Numerical value
〇 Numeric types consist of a combination of signed and unsigned types and a number of bits.
Signed type: int
Unsigned type: uint
Bit: 8,16,32,64
The absence of bit number is implementation-dependent.
〇 Literals include decimal, octal, and hexadecimal.
Example: Decimal-123, Octal-0123, Hexadecimal-0x07
〇 Type conversion is changed by Type (value).
a:=12.0
b:=uint(a)
3.Float
〇 It consists of a combination of a floating-point type (float) and a number of bits (32, 64). Literals can be expressed as, for example, 3.14 or 1.5e-2.
a:=1.25e-5
fmt.Printf("%T\n", a)
4.Complex type
〇 There are complex64 and complex128 types.
var i complex64
i=1+4i
5.Rune
〇 This type handles character codes. You can convert it back to a character with a string (rune_value)
s:="test"
for _,r:=range s{
fmt.Println(string(r))
}
6.String
〇 Use RAW strings when writing strings that span multiple lines.
var s string
s="おはよう"
fmt.Println(s)
text:=`
隣の客は
よく
柿食う客だ
`
fmt.Println(text)
7.Arrays
It is a type that cannot change size and contains the same type of data.
//Size:3
a:=[3]int{1,2,3}
//If only a declaration is made, the initial value is stored.
var b [4]int
//Assignment
a[0]=0
fmt.Println(a)
//Output
fmt.Println(b[1])
8.interface
Any type of data can be entered, but calculations, etc. will not be possible.
//If you just declare it, it will be nil, which is a valueless value.
var i interface{}
i="test"
7.Operator
Typical examples include the following:
Arithmetic operator : + , - , * , / , % , Bit operation system
Relational operator : == , != , > , >= , < , <=
Logical operator : && , ||
8.Constants
〇 Use constants when using unchanging values.
const A=1
//Same values
const (
X=1
Y
Z
)
〇 When specifying the type
const A=int64(1)
〇 iota increments by one.
const (
X=iota //0
Y //1
Z //2
)
9.Functions
〇 The basic form is "func function_name (argument_contents) return_value_type," which can be omitted if no arguments or return value is used. Multiple return values are represented by tuples and can be ignored with "_" if not used in the return value.
func swap(x,y string) (string,string){
return y,x
}
func main(){
head,_:=swap("A san","B san")
fmt.Println(head)
}
The typical way to write error handling in Go is as follows:
result,err:=do()
if(err!=nil){
//Processing when an error occurs
}
〇 An anonymous function is one that omits the function name.
f:=func(x,y int) int{return x*y}
fmt.Println(f(2,3)) //6
〇 A function can also be an argument.
package main
import "fmt"
func output(f func(int,int) int, x int,y int) bool{
result:=f(x,y)
fmt.Println(result)
return true
}
func main(){
multi:=func(x,y int)int{return x*y}
ok:=output(multi,3,4) //Output:12 Return vale:true
fmt.Println(ok) //Output:true
}
〇 The return value can also be a function, taking advantage of the closure nature of anonymous functions and allowing generators to be implemented. The following code is an example of a function that counts down with each call.
func countDown() func() int{
count:=10
return func() int{
res:=count
count-=1
return res
}
}
func main(){
f:=countDown()
fmt.Println(f())//10
fmt.Println(f())//9
//The returned function can be executed by adding ().
//Counts separately as it is a separate generator.
fmt.Println(countDown()())//10
}
10.Control statements
1.If
The conditional branch is described as follows.
func main(){
x:=10
//Conditional expression
if x==1{
fmt.Println("One")
}else if x==2{
fmt.Println("TWO")
}else{
fmt.Println("Other")
}
//If with a short statement
if a,b:="A","B";a==b{
fmt.Println("Same")
}else{
fmt.Println("Different")
}
}
2.For
Go has only one looping construct, the for loop.
〇 Infinite loop: Case used in combination with break statement
count:=0
for{
//10 times and then it's over.(break)
if count>10{
break
}
fmt.Println(count)
count++
}
〇 Conditional for statement = while
count:=0
for count<10{
fmt.Println(count)
count++
}
〇 Counts for statement: Case used in combination with continue statement
for i:=0;i<10;i++{
//Skip when even
if (i%2==0){
continue
}
fmt.Println(i)
}
〇 Extracting using "for"
var cities [3]string
cities=[3]string{"Tokyo","Pari","London"}
for i,v:=range cities{
fmt.Println(i,":",v)
}
3.Switch statement("break" is not necessary)
〇 Example
val:=3
//value switch
switch val{
case 1,2,3:
fmt.Println("1-3")
default:
fmt.Println("other")
}
//condition switch
switch {
case val%2==0:
fmt.Println("even")
case val%2==1:
fmt.Println("odd")
default:
fmt.Println("other")
}
〇 Type switch
var val interface{}=3
//Type switch
switch v:=val.(type){
case bool:
fmt.Println(v)
case int:
fmt.Println(2*v)
default:
fmt.Println("other")
}
4.Special statement(defer)
The defer statement is used for releasing resources, etc., and is executed before the function exits.
defer fmt.Println("defer")//Executed before the function exits
fmt.Println("Hello")
5.Special statement(Goroutines)
Parallel processing is executed with the Goroutines.
go func(x int){
for x<10{
fmt.Println("Parallel processing",x)
x++
}
}(1)
for i:=0;i<10;i++{
fmt.Println("Main process",i)
time.Sleep(500 * time.Millisecond)
}
11.Reference type
1.Slices
Slices are variable-length arrays.
〇 Declarations, Assignments, and References
//Declarations:value: nil
var a []int
//make
s:=make([]int,5,10)
fmt.Println(len(s)) //5
fmt.Println(cap(s)) //10
//Literal
s:=[]int{1,2,3,4,5,6}
//Assignments
s[2]=10
//References
fmt.Println(s[2]) //10
〇 Slice
//Literal
s:=[]int{1,2,3,4,5,6}
//Slice(excludes the last one)
a:=s[2:4]
for _,v:=range a{
fmt.Println(v) //3,4
}
〇 Adding the end of an element and copying
//Literal
s:=[]int{1,2,3}
//Adding the end of an element
s=append(s,4,5,6)
fmt.Println(s) //[1 2 3 4 5 6]
//Copying
a:=make([]int,len(s))
copy(a,s)
fmt.Println(a)
〇 Variable length parameter
func output(s ...string){
for _,v:=range s{
fmt.Println(v)
}
}
func main(){
//Use 1
output("A1","B1","C1")
//Use 2
s:=[]string{"A2","B2","C2"}
output(s...)
}
2.Maps
Maps=Dict
〇 Declarations, Assignments, and References
//Declarations:value: nil
var m map[int]string
//make
m1:=make(map[int]string)
//Assignments: Overwrites the value if it exists.
m1[1]="A"
m1[2]="B"
//References 1
fmt.Println(m1[2])
//References 2
_,ok:=m1[9]
fmt.Println(ok) //false
〇 Literal、For
//Literal
m:=map[int]string{1:"Tokyo",
2:"Osaka",
3:"Nagoya",
}
//Size
fmt.Println(len(m))
//Delete
delete(m,2)
//For
for k,v:=range m{
fmt.Printf("%d %s\n",k,v)
}
3.Pointers
A pointer holds the memory address of a value.
///Declarations:value: nil
var p *int
var i int
//Assignments
p=&i
i=2
//Dereferencing: i=5
*p=5
〇 Example code that takes an array as an argument and doubles the array in the argument.
func double(a *[3]int){
i:=0
for i<3{
//(*a)[i] ok
a[i]=2*a[i]
i++
}
}
func main(){
a:=[3]int{1,2,3}
//[2 4 6]
double(&a)
}
4.Channels
Channel is a data type for passing data for asynchronous processing.
〇 Declarations, Sending and receiving data.
//Declarations
var ch chan int
//Receive only (received from channel)
var ch1 <-chan int
//Send only (sent to channel)
var ch2 chan<- int
//make(Numbers represent buffer size)
ch:=make(chan int,5)
//Channel receives data.
ch<-5
//Channel sends data
i:=<-ch
〇 If there are no more values to send, it can close. Sending to a channel that is closed will result in panic. When using a channel in a range, you can signal the end of the range by closing it.
//Arrows can be omitted.
func fibonacci(n int, c chan<- int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
}
〇 "select" waits until one of several cases is ready. If multiple cases are ready, they are selected at random.
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}
12.Structs
A struct is a collection of fields.
〇 Definitions, declarations, assignments, references, compound literals
//Alias the information defined in struct by type
type User struct{
Name string
Age int
}
func main(){
//Declarations:values:default
var u User
//Assignments
u.Name="A"
//References
fmt.Println(u.Name)
//Compound literals
u2:=User{Name:"B",Age:30}
}
〇 Structure containing structure
type Address struct{
Code int
}
type User struct{
Name string
Address Address
}
func main(){
//Literal
u:=User{
Name:"A",
Address:Address{
Code:100,
},
}
//References:Output:100
fmt.Println(u.Address.Code)
}
〇 Structure pointer generation (Structure is passed by value).
//Generation 1
p:=new(User)
//Generation 2
p1:=&User{Name:"A"}
〇 Methods and alternate constructors
type Rectangle struct{
Height int
Width int
}
//Alternate constructors
func NewRectangle(h,w int) *Rectangle{
return &Rectangle{
Height:h,
Width:w,
}
}
//Area Calculation
func (r *Rectangle) Area() float64{
return float64(r.Height)*float64(r.Width)
}
func main(){
r:=NewRectangle(5,4)
fmt.Println(r.Area())
//map
m:=map[Rectangle]string{
{Height:5,Width:4}:"test1",
{Height:10,Width:3}:"test2",
}
for k,v:=range m{
fmt.Println(k.Area(),v)
}
}
〇 Interfaces
It is not necessary to declare which interface to implement.
type Animal interface{
Bark()
GetName() string
}
type Dog struct{
Name string
}
type Cat struct{
Name string
}
func (d *Dog) Bark(){
fmt.Println("bowwow")
}
func (d *Dog) GetName()string{
return d.Name
}
func (c *Cat) Bark(){
fmt.Println("mew")
}
func (c *Cat) GetName()string{
return c.Name
}
func main(){
animals:=[]Animal{
&Dog{Name:"Tarou"},
&Cat{Name:"Tama"},
}
for _,v:=range animals{
fmt.Println(v.GetName())
v.Bark()
}
}
この記事が気に入ったらサポートをしてみませんか?