Go language introduction structure & Practice

Keywords: Go JSON

Structure & Practice

structural morphology

Definition

The object-oriented in Go is realized by struct, which is a user-defined type

//Define structure
/Define structure
type User struct {
   Name       string
   Gender     string
   Age        int
   AvatarUrl  string
}

func useStruct() {
   //Initialize structure 1
   var user1 User
   user1.Name = "jeson"
   user1.Gender = "male"
   user1.Age  = 20
   user1.AvatarUrl = "http://baidu.com"
   //Initializing structure 2
   user2 := User{
      Name:      "miky",
      Gender:    "female",
      Age:       18,
   }
   fmt.Println(user1,user2)
   //Empty structure
   user3 := User{}
   fmt.Println(user3)
}

Characteristics of structure

  • Memory layout of struct: occupying a continuous memory space
  • The structure has no constructor and needs to be implemented by itself
//Define structure
type User struct {
   Name       string
   Gender     string
   Age        int
   AvatarUrl  string
}

// Define constructor
func NewUser(name,gender string,age int,url string) User {
   var user User
   user.Name = name
   user.Gender = gender
   user.Age = age
   user.AvatarUrl = url
   return user
}
//Using constructors
func main() {
   user1 := NewUser("zhansan","male",23,"xxx")
   fmt.Println(user1)
}

Use of anonymous fields and nesting

type People struct {
   Name        string
   Gender      string
   Age         int
   AvatarUrl   string
   //Anonymous field
   int
   string
   //Nested structure
   address      Address
}
type Address struct {
   City       string
   Province   string
}

func nimingStructs() {
   var people People
   people.Name = "abc"
   people.Gender = "male"
   people.AvatarUrl = "www.qq.com"
   //Reference anonymous field directly with structure name
   people.int = 99
   people.string = "hello world"
   //Use of nested structures
   people.address.City = "beijing"
   people.address.Province = "beijing"
   fmt.Printf("%#v\n",people)
   //
   people1 := People{
      Name:      "alley",
      Gender:    "male",
      Age:       12,
      AvatarUrl: "www.baidu.com",
      int:       0,
      string:    "dd",
      address:   Address{
         City: "Lanzhou",
         Province: "Gansu",
      },
   }
   fmt.Printf("%#v\n",people1)
}
  • Anonymous structures: Inheritance
  • Field visibility: upper case indicates public access, lower case indicates private access

tag and application of structure

tag is the original information of the structure, which can be read out by reflection mechanism during operation

type User struct {
   Name     string    `json:"name"`
   Gender   string   `json:"gender"`
   Age      int     `json:"age"`
   AvatarUrl string   `json:"avataurl"`
}

func jsonMarshal () {
   var user User
   user.Name = "jeck"
   user.Gender = "male"
   user.Age = 20
   user.AvatarUrl = "xxx"

   //json format
   data,err := json.Marshal(user)
   if err != nil {
      fmt.Printf("marshal failed %v\n",err)
      return
   }
   fmt.Printf("json:%v\n",string(data))
}

Practice

  • Print prime numbers in 1-100
func isPrime(n int) bool {
   var flag = true
   for j:=2;j<n;j++ {
      if (n%j==0) {
         flag = false
         break
      }
   }
   return flag
}

func zhishu() {
   var n int
   fmt.Printf("Please input n:\n")
   fmt.Scanf("%d",&n)
   for i := 2;i<n;i++ {
      if isPrime(i) {
         fmt.Printf("%d is prime\n",i)
      }
   }
}
  • Enter a line of characters to count the number of cluster letters, spaces and other characters

v1 initial version

func main() {
   str := "how are you! i am fine! thank you.welcome"
   var tmp []rune
   var wordCount map[string]int = make(map[string]int,10)
   var chars []rune = []rune(str)
   for i:=0; i<len(str);i++ {
      if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z') {
         tmp = append(tmp,chars[i])
      }else {
         word := string(tmp)
         if len(word) > 0 {
            count,ok := wordCount[word]
            if !ok {
               wordCount[word] = 1
            } else {
               wordCount[word] = count+1
            }
         }
         tmp = tmp[0:0]
      }
   }
   if len(tmp) > 0{
      word := string(tmp)
      if len(word) > 0 {
         count,ok := wordCount[word]
         if !ok {
            wordCount[word] = 1
         } else {
            wordCount[word] = count+1
         }
      }

   }
   for key,val := range wordCount {
      fmt.Printf("word:%s,Number of occurrences%d\n",key,val)
   }
}

v2 function Abstract version

func addWorld(wordCount map[string]int,chars []rune) {
   word := string(chars)
   if len(word) > 0 {
      count,ok := wordCount[word]
      if !ok {
         wordCount[word] = 1
      } else {
         wordCount[word] = count+1
      }
   }
}

func main() {
   str := "how are you! i am fine! thank you.welcome"
   var tmp []rune
   var wordCount map[string]int = make(map[string]int,10)
   var chars []rune = []rune(str)
   for i:=0; i<len(str);i++ {
      if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z') {
         tmp = append(tmp,chars[i])
      }else {
         addWorld(wordCount,tmp)
         tmp = tmp[0:0]
      }
   }
   if len(tmp) > 0{
      addWorld(wordCount,tmp)
   }
   for key,val := range wordCount {
      fmt.Printf("word:%s,Number of occurrences%d\n",key,val)
   }
}
  • Character statistics (including Chinese)
func addWord(charCount map[rune]int,char rune){
   count,ok := charCount[char]
   if !ok {
      charCount[char] = 1
   }else {
      charCount[char] = count +1
   }
}

func main() {
   str := "sds sds,Let us go go go,Good learning any sds!@lili"
   var charCount map[rune]int = make(map[rune]int,10)
   var chars []rune = []rune(str)

   for i:=0;i<len(chars);i++ {
      addWord(charCount,chars[i])
   }

   for key,val := range charCount {
      fmt.Printf("keys:%c val: %d\n",key,val)
   }
}
  • Realize a student management system, each student has score, grade, gender, name and other information, users can add students in the console, modify student information, print student list function
type Student struct {
   Id         string     `json:"id"`
   Name       string     `json:"name"`
   Age        int         `json:"name"`
   Gender     string      `json:"gender"`
   Score      float32     `json:"score"`
}

func showMenu()  {
   fmt.Printf("please select:\n")
   fmt.Printf("1. Add student information\n")
   fmt.Printf("2. Modify student information\n")
   fmt.Printf("3. Show student information\n")
   fmt.Printf("4. Sign out\n")
}

func getStudentInfo() Student {
   var stu Student
   fmt.Printf("please input id:\n")
   fmt.Scanf("%s\n",&stu.Id)
   fmt.Printf("please input name:\n")
   fmt.Scanf("%s\n",&stu.Name)
   fmt.Printf("please input age:\n")
   fmt.Scanf("%d\n",&stu.Age)
   fmt.Printf("please input gender:\n")
   fmt.Scanf("%s\n",&stu.Gender)
   fmt.Printf("please input score:\n")
   fmt.Scanf("%f\n",&stu.Score)
   return stu
}

func addStudent(allStudent map[string]Student)  {
   stu := getStudentInfo()
   _,ok := allStudent[stu.Id]
   if ok {
      fmt.Printf("student %s is exists\n",stu.Id)
      return
   }
   allStudent[stu.Id] = stu
}

func showStudentList(allStudent map[string]Student) {
   for _,val := range allStudent {
      fmt.Printf("#########Divider line##########\n")
      fmt.Printf("id:%s\n",val.Id)
      fmt.Printf("name:%s\n",val.Name)
      fmt.Printf("age:%d\n",val.Age)
      fmt.Printf("gender:%s\n",val.Gender)
      fmt.Printf("score:%f\n",val.Score)
      fmt.Printf("#########Divider line##########\n")

   }
}

func modifyStudent(allStudent map[string]Student)  {
   stu := getStudentInfo()
   _,ok := allStudent[stu.Id]
   if !ok {
      fmt.Printf("student %s is not exists\n",stu.Id)
      return
   }
   allStudent[stu.Id] = stu
}

func main() {
   var allStudent map[string]Student = make(map[string]Student,100)
   for {
      showMenu()
      var sel int
      fmt.Scanf("%d\n",&sel)
      switch sel {
      case 1:
         addStudent(allStudent)
      case 2:
         modifyStudent(allStudent)
      case 3:
         showStudentList(allStudent)
      case 4:
         os.Exit(0)
      }
   }
}

Posted by godwisam on Thu, 26 Mar 2020 09:09:21 -0700