Go:类型 []string 没有 len 字段或方法。

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

Go: type []string has no field or method len

问题

我正在尝试编译以下函数:

func (self algo_t) chk_args(args []string) {
    if len(args) != self.num_args {
        fmt.Fprintf(
            os.Stdout,
            "%s expected %d argument(s), received %d\n",
            self.name,
            self.num_args,
            len(args),
        )
        fmt.Printf("quickcrypt %s\n", self.usage)
    }
}

我收到了错误信息:“args.len未定义(类型[]string没有len字段或方法)”。

args的类型是[]string,语言规范这是一个切片类型。builtin包的文档切片类型定义了v.len()。发生了什么?

英文:

I am trying to compile the following function:

func (self algo_t) chk_args(args []string) {
	if args.len() != self.num_args {
		fmt.Fprintf(
			os.Stdout,
			"%s expected %d argument(s), received %d\n",
			self.name,
			self.num_args,
			args.len(),
		)
		fmt.Printf("quickcrypt %s\n", self.usage)
	}
}

I am receiving the error, args.len undefined (type []string has no field or method len).

Args is of type []string, and the language specification says this is a slice type. The builtin package documentation says v.len() is defined for Slice types. What is going on?

答案1

得分: 8

len不是一个方法,而是一个函数。也就是说,使用len(v)而不是v.len()

英文:

len isn't a method, it's a function. That is, use len(v) and not v.len()

答案2

得分: 1

尝试使用:

func (self *algo_t) chk_args(args []string) {
    if len(args) != self.num_args {
        fmt.Fprintf(
            os.Stdout,
            "%s 期望 %d 个参数,实际接收到 %d 个\n",
            self.name,
            self.num_args,
            len(args),
        )
        fmt.Printf("quickcrypt %s\n", self.usage)
    }
}

func len(v Type) int 是一个内置函数,允许你传入一个变量,而不是一个类型的内置函数。

另外,你可能希望将 chk_args 定义为 algo_t 指针的方法,就像我在示例中所做的那样。

英文:

Try using:

func (self *algo_t) chk_args(args []string) {
    if len(args) != self.num_args {
        fmt.Fprintf(
            os.Stdout,
            "%s expected %d argument(s), received %d\n",
            self.name,
            self.num_args,
            len(args),
        )
        fmt.Printf("quickcrypt %s\n", self.usage)
    }
}

func len(v Type) int is a built in function that allows you to pass in a variable, not a built in function on a type.

As a side note, you probably want chk_args to be a function on a pointer to algo_t like I have in the example.

huangapple
  • 本文由 发表于 2014年4月24日 02:22:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/23252282.html
匿名

发表评论

匿名网友

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

确定