如何在Go中使用另一个包中的类型声明变量?

huangapple go评论89阅读模式
英文:

How do I declare a variable with a type from another package in Go?

问题

例如:

package foo

import (
    "appengine/blobstore"
)

func main() {
    var blob blobstore.BlobInfo
    ...
}

给我这个错误:
undefined: BlobInfo

有没有办法让我能够创建这个结构体而不必复制代码?

英文:

For example:

package foo

import (
    "appengine/blobstore"
)

func main() {
    var blob blobstore.BlobInfo
    ...
}

Gives me this error:
undefined: BlobInfo

Is there a way for me to be able to create this struct without having to copy the code over?

答案1

得分: 3

如果blobstore.BlobInfo是一个类型,那么在另一个包中声明一个该类型的变量,如下所示:

var blob blobstore.BlobInfo

语法

var foo = bar.Qux

尝试创建变量foo并通过将bar.Qux的_值_赋给它来初始化,同时推断出bar.Qux的_类型_。

编辑:

要声明一个类型为T的变量

var v T

T可以来自其他包。例如

import "foo/bar"
import baz "qux"
import . "whatever"

var v1 bar.T
var v2 baz.T
var v3 T // whatever.T

如果这对你不起作用,那么可能的问题有:

  • blobstore未安装。
  • 在GOPATH中使用OP中显示的导入路径未找到包blobstore
英文:

If blobstore.BlobInfo is a type then declare a variable of that type in another package like:

var blob blobstore.BlobInfo

The syntax

var foo = bar.Qux

attempts to create var foo and initialize it by assigning it the value of bar.Qux while inferring bar.Qux's type.

EDIT:

To declare a variable of type T

var v T

T can come from other package. For example

import "foo/bar"
import baz "qux"
import . "whatever"

var v1 bar.T
var v2 baz.T
var v3 T // whatever.T

If this doesn't work for you then some of the possible problems are:

  • Package blobstore is not instaled.
  • Package blobstore is not found in your GOPATH using the import path shown in the OP.

huangapple
  • 本文由 发表于 2013年3月4日 14:11:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/15195598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定