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.