dongzhao5834 2015-03-31 18:15
浏览 21
已采纳

从另一个包引用结构域

I have the following folder structure:

.
├── Makefile
├── README.md
├── myproject
│   ├── handlers
│   │   └── authorize_handler.go
│   ├── models
│   │   ├── id_token.go
│   ├── server.go

From authorize_handler.go I try to reference the IdToken.idType field from the id_token.go file.

authorize_handler.go

package handlers

import (
    "encoding/json"
    "log"
    "net/http"

    "myproject/models"
)

func AuthorizeHandler(rw http.ResponseWriter, req *http.Request) {
    idToken := new(models.IdToken)

    decoder := json.NewDecoder(req.Body)
    err := decoder.Decode(&idToken)
    if err != nil {
        panic(err)
    }

    log.Println(idToken.idType)
}

id_token.go

package models

type IdToken struct {
    id     string `json:"id" type:"string" required:"true" max_length:"50"`
    idType string `json:"idType" type:"idType" required:"false"`
}

When I start server.go using go run server.go I get the following error:

handlers/authorize_handler.go:29: idToken.idType undefined (cannot refer to unexported field or method idType)

Moving the IdToken to the authorize_handler.go does solve the problem. Changing idType to IdType does not.

Any ideas or pointers to share?

  • 写回答

1条回答 默认 最新

  • dongqian8265 2015-03-31 18:22
    关注

    The only way it will work as you currently have it imported is if the myproject/models package is in your $GOPATH/src directory, since that is where it is looking for it when you tell it to import without a file path.

    Alternatively, you could reference using a relative path such as ../models but that can get messy. Also, this sort of file structure tends to lead to cyclical dependencies, so be aware of making sure you avoid that if you go with this method.

    Edit: As captncraig pointed out, the compiler seems to find the package ok, so this is more likely that your field within the struct is not exported because it starts with a lowercase character in the definition. Just changing it to a capital letter will make it publicly accessible from outside the package.

    type IdToken struct {
        Id     string `json:"id" type:"string" required:"true" max_length:"50"`
        IdType string `json:"idType" type:"idType" required:"false"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据