I'm planning to create some method extension for the string type.
I need to write all my extension methods into a separate package.
here is my hierarchy.
root
| main.go
| validation
| validate.go
on the main.go
I would like to have, "abcd".Required()
main.go
package main
import (
"fmt"
"./validation"
)
func main() {
fmt.Println( "abcd".Required() )
}
validate.go
package validation
func (s string) Required() bool {
if s != "" {
return true
}
return false
}
When I run it, will get an error.
error
cannot define new methods on non-local type string
I found some answers in other questions on StackOverflow but they don't exactly talk about the string type & having the method in a different package file.
In your validate.go create a new type String
:
package validation
type String string
func (s String) Required() bool {
return s != ""
}
And then work with validation.String
objects in your main:
package main
import (
"fmt"
"./validation"
)
func main() {
fmt.Println(validation.String("abcd").Required())
}
An executable example with it all in the same file here:
https://play.golang.org/p/z_LcTZ6Qvfn
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With