Go語言程式:將字串轉換為物件


在 Go 語言程式中,字串是一種包含字面量和字元的資料型別,而物件是由類建立的資料型別,它將相似型別的屬性組合在一起。本文將介紹兩種在 Go 語言中將字串轉換為物件的方法。

語法

func Split(str, sep string) []string

Split() 函式用於透過提供的分隔符分割字串。此函式位於 strings 包中,它接受要分割的字串和分隔符作為引數。然後,該函式返回最終的字串陣列作為結果。

func typeofobject(x interface{})

typeof() 函式用於獲取任何變數的型別。此函式位於 reflect 包中,它接受要確定其型別的變數作為引數。然後,該函式返回指定變數的型別作為結果。

func Atoi(s string) (int, error)

Atoi() 函式位於 strings 包中,用於將字串轉換為整數值。該函式接受字串值作為引數,並在轉換後返回相應的整數值。該函式還返回一個錯誤變數,如果在生成輸出時出現問題,則該變數包含錯誤。

func ValueOf(i interface{}) Value

VslueOf() 函式位於 reflect 包中,用於獲取初始化為介面 i 中儲存的具體值的新值。要訪問此函式,程式需要匯入 reflect 包。

演算法

  • 步驟 1 - 首先,我們需要匯入 fmt、json 和 reflect 包。

  • 步驟 2 - 然後,建立一個名為 user 的結構體,並將 Name 和 Age 作為其屬性儲存。

  • 步驟 3 - 然後,建立 main() 函式。建立一個名為 input 的字串變數,並向其中儲存值。

  • 步驟 4 - 接下來,建立一個名為 user 的空變數,型別為 User。此外,在螢幕上列印字串變數。

  • 步驟 5 - 現在,呼叫 json 包中存在的 Unmarshal() 方法,並將 input 變數作為位元組陣列作為引數傳遞給該函式以及 user 結構體。

  • 步驟 6 - 如果轉換過程成功,則不會顯示任何錯誤。使用 fmt.Println() 在螢幕上列印最終結果。

示例 1:使用 Json 包

在此程式中,我們將使用 json 包將字串轉換為物件。

package main
import (
   "encoding/json"
   "fmt"
   "reflect"
)

type User struct {
   Name string
   Age  int
}

func main() {
   input := `{"Name": "Alice", "Age": 25}`
   var user User
   fmt.Println("The given string is:", input, "and its type is:", reflect.TypeOf(input))
   err := json.Unmarshal([]byte(input), &user)
   if err != nil {
      fmt.Println(err)
      return
   }
   fmt.Println()
   fmt.Printf("The object created from the above string is: %+v\n", user)

}

輸出

The given string is: {"Name": "Alice", "Age": 25} and its type is: string

The object created from the above string is: {Name:Alice Age:25}

示例 2:使用 Reflect 包

在此示例中,我們將編寫一個 Go 語言程式,使用 reflect 包將字串轉換為物件。

package main
import (
   "fmt"
   "reflect"
   "strconv"
   "strings"
)

// creating user structure
type User struct {
   Name string
   Age  int
}

func main() {
   input := "Name:Alice Age:25"
   fmt.Println("The given string is:", input, "and its type is:", reflect.TypeOf(input))
   values := strings.Split(input, " ")
   user := User{}
   // using for loop to iterate over the string
   for _, value := range values {
      parts := strings.Split(value, ":")
	  if len(parts) != 2 {
	      continue
	   }
	   key, val := parts[0], parts[1]
	   v := reflect.ValueOf(&user).Elem()
	   f := v.FieldByName(key)
	   if !f.IsValid() {
	      continue
	   }
	   if f.Type().Kind() == reflect.Int {
	      age, err := strconv.Atoi(val)
		  if err != nil {
		     continue
		  }
		  f.SetInt(int64(age))
	   } else {
			f.SetString(val)
	   }
   }
   fmt.Printf("The object obtained after converting string to object is: %+v\n", user)
}

輸出

The given string is: Name:Alice Age:25 and its type is: string
The object obtained after converting string to object is: {Name:Alice Age:25}

結論

我們已經成功編譯並執行了一個 Go 語言程式,用於將字串轉換為物件,並附帶示例。我們在第一個程式中使用了 json 包,在第二個程式中使用了 reflect 包。

更新於: 2023年2月16日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.