How to use golang
This article is to share with you about how to use golang. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. Using defer and recover to realize try...catch
Func Try (fun func (), handler func (interface {})) {defer func () {if err: = recover () Err! = nil {handler (err)}} () fun ()} func main () {Try (func () {panic ("foo")}, func (e interface {}) {print (e)})}
two。 A program about error
Error is a type, and similar to string,error, you can define your own type.
Package mainimport "errors" import "fmt" / / By convention, errors are the last return value and// have type `error`, a built-in interface.func F1 (arg int) (int, error) {if arg = = 42 {/ / `errors.New`constructs a basic `error`value / / with the given error message. Return-1, errors.New ("can't work with 42")} / / A nil value in the error position indicates that / there was no error. Return arg + 3, nil} / / It's possible to use custom types as `error`s by// implementing the `Error () `method on them. Here's a func / variant on the example above that uses a custom type// to explicitly represent an argument error.type argError struct {arg int prob string} func (e * argError) Error () string {return fmt.Sprintf ("% d -% s", e.arg, e.prob)} func f2 (int, error) {if arg = = 42 {/ / In this case we use `& argError` syntax to build / / a new struct Supplying values for the two / / fields `arg`and `prob`. Return-1, & argError {arg, can't work with it}} return arg + 3, nil} func main () {/ / The two loops below test out each of our / / error-returning functions. Note that the use of an / / inline error check on the `if` line is a common / / idiom in Go code. For _, I: = range [] int {7,42} {if r, e: = F1 (I); e! = nil {fmt.Println ("F1 failed:", e)} else {fmt.Println ("F1 worked:", r)}} for _, I: = range [] int {7,42} {if r, e: = f2 (I) E! = nil {fmt.Println ("f2 failed:", e)} else {fmt.Println ("f2 worked:", r)}} / / If you want to programmatically use the data in / / a custom error, you'll need to get the error as an / / instance of the custom error type via type / / assertion. _, e: = f2 (42) if ae, ok: = e. (* argError); ok {fmt.Println (ae.arg) fmt.Println (ae.prob)}}
3. Both timer and ticker can be stopped.
Package mainimport ("fmt"time") func main () {ticker: = time.NewTicker (time.Millisecond * 500) go func () {for t: = range ticker.C {fmt.Println ("ticker is at") T)} () time.Sleep (time.Millisecond * 1500) ticker.Stop () fmt.Println ("ticker stopped")} package mainimport ("fmt"time") func main () {timer1: = time.NewTimer (time.Second * 2)