struct Point { int id; string name; string intro; Point(){} Point(int i, string n, string in) : id(i), name(n), intro(in) {} };
时间: 2024-02-16 10:27:25 浏览: 28
这段代码定义了一个名为 `Point` 的结构体,包含三个成员变量:id、name、intro。其中,id 是点的唯一标识符,name 是点的名称,intro 是点的介绍。该结构体还提供了两个构造函数:一个无参构造函数和一个有参构造函数,有参构造函数接收三个参数,分别是点的 id、name 和 intro,用于创建一个新的 `Point` 对象。
相关问题
go 结构体中 struct int互转string
在 Golang 中,可以使用 strconv 包中的函数将 int 类型转换为 string 类型,也可以使用 fmt.Sprintf() 函数将 int 类型格式化为 string 类型。同样,也可以将 string 类型转换为 int 类型。
以下是一个示例代码,演示了如何在嵌套的结构体中将 int 类型转换为 string 类型:
```go
package main
import (
"fmt"
"strconv"
)
type Person struct {
Name string
Age int
}
type Company struct {
Name string
Employee Person
FoundedAt int
}
func (p Person) String() string {
return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}
func (c Company) String() string {
return fmt.Sprintf("%v, founded in %v, employee: %v", c.Name, c.FoundedAt, c.Employee)
}
func main() {
p := Person{"John", 30}
c := Company{"Golang Inc.", p, 2009}
// 将 int 类型转换为 string 类型
c.FoundedAt = 2010
fmt.Println(c) // Golang Inc., founded in 2010, employee: John (30 years)
// 将 string 类型转换为 int 类型
foundedAt, err := strconv.Atoi("2009")
if err != nil {
fmt.Println(err)
}
c.FoundedAt = foundedAt
fmt.Println(c) // Golang Inc., founded in 2009, employee: John (30 years)
}
```
在上面的示例代码中,我们定义了两个结构体:Person 和 Company。Company 结构体中包含一个 Person 类型的嵌套结构体 Employee 和一个 int 类型的字段 FoundedAt。
在 Person 结构体中,我们定义了一个 String() 方法,用于将结构体格式化为字符串。
在 Company 结构体中,我们也定义了一个 String() 方法,用于将结构体格式化为字符串。在该方法中,我们使用 fmt.Sprintf() 函数将 Employee 结构体格式化为字符串,并将 int 类型的 FoundedAt 字段转换为 string 类型。
在 main() 函数中,我们创建了一个 Person 类型的变量 p 和一个 Company 类型的变量 c,其中 c 的 Employee 字段为 p。我们使用 fmt.Println() 函数将 c 变量打印出来,以检查它的 Employee 和 FoundedAt 字段是否已正确转换为 string 类型或 int 类型。
golang type ThreeScene struct 内为int64 转为json为string
要将 Golang 中的 `int64` 类型转换为 JSON 字符串,可以使用 `strconv` 包中的 `Itoa` 函数将 `int64` 转换为 `string` 类型,然后再使用 `encoding/json` 包中的 `Marshal` 函数将 `struct` 类型转换为 JSON 字符串。
下面是一个将 `ThreeScene` 结构体类型转换为 JSON 字符串的示例代码:
```go
import (
"encoding/json"
"strconv"
)
type ThreeScene struct {
SceneID int64 `json:"scene_id"`
// 其他字段...
}
func main() {
scene := ThreeScene{SceneID: 1234567890}
// 将 int64 类型转换为 string 类型
sceneIDStr := strconv.Itoa(int(scene.SceneID))
// 将 struct 类型转换为 JSON 字符串
sceneJSON, err := json.Marshal(scene)
if err != nil {
panic(err)
}
// 输出 JSON 字符串
fmt.Println(string(sceneJSON))
}
```
在上面的示例代码中,首先定义了一个 `ThreeScene` 结构体类型,并且在其中定义了一个 `int64` 类型的字段 `SceneID`。接下来,在 `main` 函数中,定义了一个 `ThreeScene` 类型的变量 `scene`,并且将其 `SceneID` 字段设置为 1234567890。然后,使用 `strconv.Itoa` 函数将 `int64` 类型转换为 `string` 类型,并将结果保存在 `sceneIDStr` 变量中。最后,使用 `json.Marshal` 函数将 `scene` 变量转换为 JSON 字符串,并将结果输出到控制台。
注意,在上面的示例代码中,为了让 JSON 字符串中的字段名为小写字母,我们在 `ThreeScene` 结构体中使用了 `json:"scene_id"` 标签。如果不需要这个标签,可以直接将结构体中的字段名改为大写字母。