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
",
self.name,
self.num_args,
args.len(),
)
fmt.Printf("quickcrypt %s
", 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?
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
",
self.name,
self.num_args,
len(args),
)
fmt.Printf("quickcrypt %s
", 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.
len
isn't a method, it's a function. That is, use len(v)
and not v.len()