首页 > 解决方案 > 您将如何解释这种类型的语法(强制转换)?

问题描述

查看c.Organizations = (*OrganizationsService)(&c.common)来自https://github.com/google/go-github/blob/master/github/github.go#L283的源代码,在用适当的术语描述这段代码时,您是否将其描述如下:

变量 c 的 Organizations 字段设置为 c.common 的地址,该地址被转换为 OrganizationsService 的指针接收器值。

或者我在描述这个时错过了一些细微差别?

下面是一些相关的源代码,显示了变量的定义位置。

// A Client manages communication with the GitHub API.
type Client struct {
    clientMu sync.Mutex   // clientMu protects the client during calls that modify the CheckRedirect func.
    client   *http.Client // HTTP client used to communicate with the API.

    // Base URL for API requests. Defaults to the public GitHub API, but can be
    // set to a domain endpoint to use with GitHub Enterprise. BaseURL should
    // always be specified with a trailing slash.
    BaseURL *url.URL

    // Base URL for uploading files.
    UploadURL *url.URL

    // User agent used when communicating with the GitHub API.
    UserAgent string

    rateMu     sync.Mutex
    rateLimits [categories]Rate // Rate limits for the client as determined by the most recent API calls.

    common service // Reuse a single struct instead of allocating one for each service on the heap.

    // Services used for talking to different parts of the GitHub API.
    Actions        *ActionsService
    Activity       *ActivityService
    Admin          *AdminService
    Apps           *AppsService
    Authorizations *AuthorizationsService
    Checks         *ChecksService
    CodeScanning   *CodeScanningService
    Enterprise     *EnterpriseService
    Gists          *GistsService
    Git            *GitService
    Gitignores     *GitignoresService
    Interactions   *InteractionsService
    IssueImport    *IssueImportService
    Issues         *IssuesService
    Licenses       *LicensesService
    Marketplace    *MarketplaceService
    Migrations     *MigrationService
    Organizations  *OrganizationsService
    Projects       *ProjectsService
    PullRequests   *PullRequestsService
    Reactions      *ReactionsService
    Repositories   *RepositoriesService
    Search         *SearchService
    Teams          *TeamsService
    Users          *UsersService
}

type service struct {
    client *Client
}

标签: go

解决方案


变量 c 的 Organizations 字段设置为 c.common 的地址,该地址被转换为 OrganizationsService 的指针接收器值。

这很接近,但我会做一些改变。

第一的:

铸造

根据官方 Go 术语,这里进行的操作是“转换”而不是强制转换。

第二:

c 设置为c.common的地址...

虽然&是“寻址”运算符,但它产生的值是一个指针值。该值的文字内容是地址。引用地址并没有错,但是在分析语法和结构时,我们可能更愿意引用高层的值,而不是它们的内容。

第三:

指针接收器值...

Go 中的“接收者”一词是指方法调用或方法声明中的接收者值,例如

func (v *Value) Method()  {
    
}

v是接收器,它的类型确实是指针类型,但不一定是。

func (v Value) Method()  {
    
}

这也是有效的(尽管与第一个版本相比可能有不同的和意想不到的效果)。无论如何,您问题中的价值在任何意义上都不是接收者。

随着调整:

变量 c 的 Organizations 字段设置为指向 c.common 的指针,该指针转换为指向 OrganizationsService 类型的指针值。

即使如此,我们也可以稍微重构一下句子,使其更类似于程序中发生的操作顺序。从左到右分析事物似乎很自然,但这很少是最容易理解的代码表达方式。

在我看来,这是一个更自然的解释。

指向 c 的“common”字段的指针被转换为指向 OrganizationsService 的指针,然后分配给 c 的“Organizations”字段。


推荐阅读