Detailed introduction to golang structure forced transfer

PHPz
Release: 2023-03-30 09:47:20
Original
1878 people have browsed it

In Go language, structure is a very common data type. A structure is a collection defined by a set of types. Each structure can contain multiple fields, each with its own name and type. In actual development, we often use structure type conversion, which is to force one structure type to another structure type. Next, this article will give you a detailed introduction to golang structure forced transfer.

Golang structure type coercion mainly has the following three methods:

Method 1: Use type assertion

In Go language, you can use type assertion (Type Assertion) To implement structure type coercion. Type assertions can be used to determine whether the value stored in an interface variable is a specific type, or to convert the interface type to other types. The following is an example:

type Person struct { Name string Age int } type Student struct { Name string Age int Grade int } func main() { var p Person p.Name = "张三" p.Age = 22 // 转换为Student类型 s, ok := interface{}(&p).(*Student) if ok { fmt.Println(s.Name, s.Age, s.Grade) } else { fmt.Println("类型转换失败") } }
Copy after login

In the above code, we cast the Person type structure p into a Student type structure. Since p is actually a Person type structure, the conversion operation will fail. In order to avoid panic, we use the ok-idiom method, that is, when performing forced type conversion, we also determine whether the result of type conversion is successful. If successful, return the new object after conversion, otherwise return nil.

Method 2: Convert to json and then convert to target structure

In addition to using type assertions for type conversion, you can also use json serialization and deserialization to implement structure types forced conversion. The specific steps are as follows:

  1. Serialize the source object into a json string.
  2. Deserialize the json string into the target object and the conversion is completed.
type Person struct { Name string Age int } type Student struct { Name string Age int Grade int } func main() { var p Person p.Name = "张三" p.Age = 22 // 转换为Student类型 b, _ := json.Marshal(&p) var s Student json.Unmarshal(b, &s) fmt.Println(s.Name, s.Age, s.Grade) }
Copy after login

In the above code, we cast the Person type structure p into a Student type structure. First, we use the json.Marshal() function to convert the source object p into a json string b; then, we use the json.Unmarshal() function to deserialize the json string b into the target object s. There is no need to determine whether the type conversion is successful because the json.Unmarshal() function does not return an error.

Method 3: Direct byte copy

In addition to using type assertions and json serialization and deserialization for type conversion, you can also directly copy bytes. The specific steps are as follows:

  1. First serialize the source structure to obtain a byte slice.
  2. Copy the byte slice to the target structure.
  3. Deserialize the target structure and the conversion is completed.
type Person struct { Name string Age int } type Student struct { Name string Age int Grade int } func main() { var p Person p.Name = "张三" p.Age = 22 // 转换为Student类型 var s Student b, _ := json.Marshal(&p) copy((*(*[1 << 20]byte)(unsafe.Pointer(&s)))[:], b) fmt.Println(s.Name, s.Age, s.Grade) }
Copy after login

In the above code, we cast the Person type structure p into a Student type structure. First, we use the json.Marshal() function to convert the source structure p into a byte array b; then, we use the copy() function to copy the byte array b into the memory space of the target structure; finally, we use json The .Unmarshal() function deserializes the target structure to complete type conversion.

Conclusion:

The above three methods can all achieve structure type conversion. In actual development, we must choose the appropriate method according to our own needs. It should be noted that when using pointer type structure conversion, special attention should be paid to issues such as deep copying of pointer values and correctness of types.

The above is the detailed content of Detailed introduction to golang structure forced transfer. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!