当前位置:网站首页>Golang Foundation (1)
Golang Foundation (1)
2022-06-09 18:17:00 【It's haohaozi】
One 、hello world
package main // Every go All the documents are written in package Beginning of sentence ,package The word gives the name of the package ,Go The code in the file is called part of the package .
import "fmt" // Each file needs to be imported into another package , Then you can use the code contained in other packages
func main () {
fmt.Println("Hello World!","Go") // Parameter use , No separation
}
package main
import (
"fmt" // Package name
"math"
"strings"
)
func main() {
fmt.Println(math.Floor(3.14)) // Call functions through packages , for example fmt( package ).Println( function )()
fmt.Println(strings.Title("head first go"))
}
character string
“Hello World!”
Rune (rune)
‘A’ // Single character
Boolean value
true,false
Declare variables
Just use var keyword , Followed by the desired name and the type of value the variable will hold .
var quality int
var length,width float64
var name string
// use = Assign any value of that type to the variable
quality=2
name="go"
// You can assign values to multiple variables at once
length,width=1.2,2.4
// If you assign a value to a variable while declaring it , You can usually omit the type of a variable from the declaration . The value type assigned to the variable will be used as the type of the variable .
var quality=2
var length,width=1.2,1.4
var name="go"
Short variable declaration
If you know what the value of a variable is when you declare it , You can use short variables to declare . You don't have to explicitly declare the type of the variable and use it later = For the assignment , But at the same time :=. If you ignore :,quality=2 Will be treated as assignment .
quality:=2 // Declaration plus definition ( simultaneous assignment )
length,width:=1.2,2.4
name:="go"
All declared variables must be used in the program .
fmt.Println(quality)
fmt.Println(length,width)
fmt.Println(name)
type
You can pass any value to reflect Bag TypeOf function , To see their types .
package main
import (
"fmt"
"reflect"
)
func main() {
fmt.Println(reflect.TypeOf(42)) //int
}
Naming rules
- The name must begin with a capital letter
If the variable 、 The name of a function or type begins with an uppercase letter , It is considered to be derived , It can be accessed from outside the current package , Otherwise, it can only be used in the current package .
transformation
Go The mathematical and comparison operations in require that the contained values have the same type . If not , An error will be reported when trying to run the code . The same is true for assigning new values to variables , An error will also be reported if the assigned type does not match the type declared by the variable .
The purpose of conversion is to allow you to convert values from one type to another . Just provide the type to convert the value to , This is followed by the value to be converted in parentheses .
var myInt int = 2
float64(myInt)
quality:=2
length:=1.2
length=float64(quality)
Two 、 Conditions and Cycles
Calling method
Go The Chinese method means : A function associated with a value of a given type . It's a bit like a member function .
In the following code time There is a in the package that represents the date and time Time type , every last time.Time Values have a return year Year Method .
package main
import (
"fmt"
"time"
)
func main() {
//time.Now Function returns a new... Of the current date and time Time value , Store it in now variable . Then on now The referenced value calls Year Method .
var now time.Time = time.Now()
var year int = now.Year()
fmt.Println(year)
fmt.Println(now)
}
Methods are functions associated with a particular type of value .
string There's a Replacer type , You can search for substrings in a string , And replace the substring with another string every time it appears :
package main
import (
"fmt"
"strings"
)
func main() {
broken:="G# r#cks!"
replacer:=strings.NewReplacer("#","o") // Will return strings.Replacer, And set each to "#" Replace with "o"
fixed:=replacer.Replace(broken)//strings.Replacer call Replace Method , And pass a string to replace
fmt.Println(fixed)
}
What is the difference between calling methods and functions ?
Function belongs to a package , The method belongs to a single value . This value appears to the left of the dot .
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Print("Enter a grade: ")
// The method that needs to read the input from the standard input of the program
//input, _ := (bufio.NewReader(os.Stdin)).ReadString('\n') // Normal output
reader:=bufio.NewReader(os.Stdin) // take bufio.Reader Save in reader variable
input:=reader.ReadString('\n') // To actually get user input , call Reader Of ReaderString Method ,ReadString Method requires a with rune To mark the end of input , That is, everything before the newline character will be read
fmt.Println(input)
}
In the above code ReadString Method attempts to return two values , In fact, an error will be reported during operation .
Go The most common use of multiple return values in is to return an additional error value (err), You can query the error value to determine whether an error has occurred in a function or method .
Go Every variable declared is required to be used everywhere in the program . If we add one err Variable , Without checking it , Our code will not compile .
The code is improved to :
input,err := reader.ReadString('\n') // error ,Go We are not allowed to declare a variable , Unless we use it .
// Use Go The blank identifier of ignores the error return value
input,_ := reader.ReadString('\n')
You can also choose to handle errors : add to log package , among Fatal function , It can complete two operations for us at the same time : Record a message to the terminal and stop the program .
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
fmt.Print("Enter a grade: ")
// The method that needs to read the input from the standard input of the program
reader:=bufio.NewReader(os.Stdin) // take bufio.Reader Save in reader variable
input,err:=reader.ReadString('\n') // To actually get user input , call Reader Of ReaderString Method ,ReadString Method requires a with rune To mark the end of input , That is, everything before the newline character will be read
log.Fatal(err)
fmt.Println(input)
}
Conditions
When running, we found that even if the program is normal, it will stop running . Return only err by nil, No error . But our program simply reports nil error , What we should do is , Only when err The value of the variable is not nil Before exiting the program .
This can be achieved using conditional statements .
input,err:=reader.ReadString('\n')
if err!=nil {
log.Fatal(err)
}
fmt.Println(input)
Convert string to number
Try writing code like this to see what's wrong .
func main() {
fmt.Print("Enter a grade: ")
reader:=bufio.NewReader(os.Stdin)
input,err:=reader.ReadString('\n')
if err!=nil {
log.Fatal(err)
}
if input >=60 {
status:="passing"
} else {
status:="failing"
}
}
What is entered from the keyboard is read as a string . There are two problems above :
- There is a newline character at the end of the input string
- The rest of the string needs to be converted to floating point numbers
terms of settlement : - strings There is one in the bag TrimSpace function , It will delete all white space characters at the beginning and end of the string ( A newline 、 Tabs and regular spaces )
input=strings.TrimSpace(input) - strconv Bag ParseFloat The function converts it to float64 value
grade,err:=strconv.ParseFloat(input,64)64 Is the precision digit of the result
block
Go Code can be partitioned , Code snippets . Blocks usually consist of curly braces {} Surround , Blocks can be nested . As in the above code , Yes if block , Function block , Package block and file block .
Scope of blocks and variables
Declared variables have a scope : Visible parts of the code . Declared variables can be accessed anywhere within their scope , But if you access it outside the scope , You will receive an error .
above status Scope is limited to if In block , Access... Outside the scope status There will be mistakes .
Here is a complete program to judge the results :
package main
import (
"fmt"
"os"
"bufio"
"log"
"strings"
"strconv"
)
func main() {
fmt.Print("Enter a grade: ")
reader:=bufio.NewReader(os.Stdin)
input,err:=reader.ReadString('\n')
if err!=nil {
log.Fatal(err)
}
input=strings.TrimSpace(input)
grade,err:=strconv.ParseFloat(input,64)
if err!=nil {
log.Fatal(err)
}
var status string
if grade >=60 {
status="passing"
} else {
status="failing"
}
fmt.Println(grade,"is",status)
}
Only one variable in the short variable declaration must be new
When a variable name is declared twice in the same scope . We'll get a compile error :
a:=1
a:=2
But as long as the short variable declaration At least One variable name is new ( There was no statement ), This is allowed . The new variable name is treated as a declaration , Existing names are treated as assignments .
a:=1 // Statement a
b,a:=2,3 // Statement b, assignment a
a,c:=4,5 // assignment a, Statement c
A small number guessing game
//guess challenge players to guess a random number
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
func main() {
seconds := time.Now().Unix() // time.Now() Will return... Representing the current date Time value ,Time call unix Method , It will convert the time to an integer
rand.Seed(seconds) // Seeding a random seed generator
target := rand.Intn(100) + 1 // rand.Intn(100) Will return 0~99 Random number of ranges
fmt.Println("I've chosen a random number between 1 and 100.")
fmt.Println("Can you guess it")
//fmt.Println(target)
reader := bufio.NewReader(os.Stdin)
success := false
for i := 0; i < 10; i++ {
fmt.Println("You have", 10-i, "guesses left!")
fmt.Println("Make a guess: ")
input, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
input = strings.TrimSpace(input) // Remove line breaks
guess, err := strconv.Atoi(input) // Change to plastic
if err != nil {
log.Fatal(err)
}
if guess > target {
fmt.Println("Your guess was HIGH!")
} else if guess < target {
fmt.Println("Your guess was Low!")
} else {
fmt.Println("Your guess was right!")
success = true
break
}
}
if !success {
fmt.Println("Sorry, you didn't guess my number. It was", target)
}
}
边栏推荐
猜你喜欢

微信小程序根据经纬度获取省市区信息

Epigentek chromatin accessibility test kit principles and procedures

C# 29. textbox始终显示最后一行

Singular Value Decomposition(SVD)

NLP-文本表示-词袋模型和TF-IDF

CNN - nn.Conv1d使用

Overview of GCN graph convolution neural network

基于Nexys3的频谱仪设计VHDL可上板

Epigentek hi fi cDNA synthesis kit instructions

Development and practice of the martyr's family search system
随机推荐
几经波折,InfluxDB的TSDB C位还能做多久?
Wake up from a dream
CNN - nn.Conv1d使用
空闲内存的管理
外汇交易MT4是什么软件?MT4与MT5有何区别?下载MT4要注意什么?
如何以案例学习kd树构建和搜索过程?
如何实现自定义富文本编辑器标签
君可归烈士寻亲系统开发实战
[notes of advanced mathematics] Green formula, Gauss formula, Stokes formula, field theory
什么是波场TRX 钱包开发
基于Nexys3的频谱仪设计VHDL可上板
What are the main applications of conductive slip rings
[work with notes] multiple coexistence of ADB, sound card, network card and serial port of Tina system
【数据处理】pandas读取sql数据
中金证券开户有什么风险吗?安全的吗?
利用go破解带密码的rar压缩文件
Epigentek btaf1 polyclonal antibody instructions
Development and practice of the martyr's family search system
图片搜索在 Dropbox 中的工作原理
华为云原生之数据仓库服务GaussDB(DWS)的深度使用与应用实践【这次高斯不是数学家】