go - 有不同的方法来设置结构字段的值吗?

标签 go

我在github.com/go-github存储库上遇到了一个代码,在那里他们使用了另一种方法来设置struct字段。我不明白该语法。示例代码如下:

package main

import (
    "fmt"
)
type Client struct{
    X int

    common service // To reuse same struct instead of creating new for each service

    Activity *ActivityService
    Reply *ReplyService
}

type ActivityService service
type ReplyService service
type service struct{
    client *Client
}


func NewClient() *Client {
    c := &Client{X:5}
    c.common.client = c


    c.Activity = (*ActivityService)(&c.common)
    c.Reply = &ReplyService{client: c}

    return c
}

func main() {
    fmt.Println("Hello, playground")
}

在此代码中,Activity字段设置为(*ActivityService)(&c.common),它在操场上不返回错误。我猜这是有效的语法。您能解释一下这种语法吗?

我知道的语法是&ReplyService{client:c}
playground link

最佳答案

c.Activity =(* ActivityService)(&c.common)

这是类型转换(https://tour.golang.org/basics/13)
例如ActivityService类型基于service类型,而c.commonservice,则可以正常工作

关于go - 有不同的方法来设置结构字段的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59683050/

相关文章:

go - 记录 http 响应(除了请求)

arrays - 如何分配 channel 数组

java - 将无符号字节流转换为有符号字节流 Golang

go - 哪个协程(goroutines 和 kotlin coroutines)更快?

go - 列出模块的依赖项,而不是包

Golang io.Pipe 与 node.js 管道

unit-testing - 如何在 Golang 的单元测试中测试 net.Conn?

json - Golang 解析带有未知键的 JSON

go - 与私有(private)接口(interface)比较

amazon-web-services - 将外部身份提供者与服务器端身份验证结合使用