我在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.common
是service
,则可以正常工作
关于go - 有不同的方法来设置结构字段的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59683050/