英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论