登录
首页 >  Golang >  Go问答

解释这种语法(类型转换)的方法是什么?

来源:stackoverflow

时间:2024-03-13 08:18:27 370浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《解释这种语法(类型转换)的方法是什么?》,涉及到,有需要的可以收藏一下

问题内容

查看源代码 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 术语,这里完成的操作是“转换”而不是强制转换。

第二:

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

第三:

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

func (v *value) method()  {
    
}

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

func (v Value) Method()  {
    
}

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

调整后:

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

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

以上就是《解释这种语法(类型转换)的方法是什么?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>