5

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.

2
  • 11
    As the error says: you can't define methods on the string type. You may however create a new type (e.g. type mystring string), and add methods to the new type. Commented Jan 24, 2019 at 13:02
  • @icza yes, that's true. i've tired that but still doesn't work as i expected. Commented Jan 25, 2019 at 4:10

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

4 Comments

return s != ""
@IainDuncan this works. tnx. but I wonder how can we have validation.String("abcd").Reqired() much simpler.
How can we actually accept any type not only string in this example?
@usr784638 if it is treating for the zero value of any field then you could do that via reflection like this question google.com/url?sa=t&source=web&rct=j&url=https://…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.