Go Language Programming Chapter 1--Getting Started

1.1 hello, world

helloworld.go

package main

import "fmt"

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

Execute go run helloworld.goRun the program.

Build and execute.

go build helloworld.go 
./helloworld

1.2 Command line parameters

The variable os.Args is a string slice.

echo1.go

package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	var s, sep string
	for i := 1; i < len(os.Args); i++ {
    
    
		s += sep + os.Args[i]
		sep = " "
	}
	fmt.Println(s)
}

If a variable is not initialized when declared, it will be implicitly initialized to a null value of this type. For example, the initialization result is 0 for numbers and the empty string "" for strings.

for is the only loop statement in Go. There are several forms.
for initialization; condition; post { // zero or more statements }

// Traditional "while" loop
for condition { // }

// Traditional infinite loop
for { // … }

Another form of for loop iterates over string or slice data.
echo2.go

package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	s, sep := "", ""
	for _, arg := range os.Args[1:] {
    
    
		s += sep + arg
		sep = " "
	}
	fmt.Println(s)
}

The following ways of declaring string variables are equivalent:

s := ""
var s string
var s = ""
var s string = ""

echo3.go

package main

import (
	"fmt"
	"os"
)
func main() {
    
    
	fmt.Println(strings.Join(os.Args[1:], " "))
}

Guess you like

Origin blog.csdn.net/houzhizhen/article/details/135238005