Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "os"
- "time"
- "github.com/pkg/errors"
- "strings"
- )
- // 1. use interfaces to interact between modules
- type Person interface {
- GetName() string
- GetAge() int
- }
- // implementation
- type Man struct {
- name string
- age int
- }
- func (m Man) GetName() string {
- return m.name
- }
- func (m Man) GetAge() int {
- return m.age
- }
- func printPerson(person Person) {
- fmt.Printf("Name %s. Age %d", person.GetName(), person.GetAge())
- }
- // 2. Do not ignore errors
- func test() error {
- // Good
- if err := os.Chown("/tmp/test", 2, 2); err != nil {
- return err
- }
- return nil
- // Bad
- // os.Chown("/tmp/test", 2, 2)
- }
- // 3. letter case struct fields are not available from other modules struct functions and cat not be serializable via Json
- func test1() {
- p := Man{}
- // Not available from foreign modules
- // p.name
- // Use methods instead
- // p.GetName()
- // Or fields starting with Upper case(BAD)
- // p.Name
- // Create special structure with upper case fields for marshalling and unmarshalling
- fmt.Printf("Data: %v", p)
- }
- // 4. for cycle
- func main1() {
- g := []int{1, 2, 3, 4, 5, 6, 7}
- // Bad
- for _, value := range g {
- go func() {
- fmt.Printf("Value is: %d \n", value)
- }()
- }
- time.Sleep(time.Duration(2) * time.Second)
- // Good
- for _, value := range g {
- // pass cycle value as function parameter!
- go func(param int) {
- fmt.Printf("Value is: %d \n", param)
- }(value)
- }
- time.Sleep(time.Duration(2) * time.Second)
- }
- // 5. if clause
- func test51() (string, error) {
- return "lol", nil
- }
- func main() {
- var res string
- // pay attention to so-called variables inside if-clause
- if res, _ := test51(); res != "" {
- // res variable scope
- fmt.Printf("Res: %s \n", res)
- }
- fmt.Printf("Res: %s \n", res)
- // do not allow golang to make decision about partially definition
- res, err := test51()
- _ = err
- // res variable scope
- fmt.Printf("Res: %s \n", res)
- }
- // 6. errors are not strings
- func test6() {
- err1 := errors.New("test error")
- err2 := errors.New("test1 error")
- if err1 == err2 {
- fmt.Printf("wtf?")
- }
- fmt.Printf("Err1: %s. Err2: %s", err1, err2)
- // please, no
- if strings.Contains(err1.Error(), "test ") {
- }
- // more advanced error handling - later
- }
- // Course: Effective go
- // https://talks.golang.org/2012/10things.slide#1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement