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.

usr784638
  • 97
  • 1
  • 7
  • 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. – icza Jan 24 '19 at 13:02
  • @icza yes, that's true. i've tired that but still doesn't work as i expected. – usr784638 Jan 25 '19 at 04:10

1 Answers1

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

Iain Duncan
  • 3,139
  • 2
  • 17
  • 28
  • 2
    `return s != ""` – Gavin Jan 24 '19 at 16:56
  • @IainDuncan this works. tnx. but I wonder how can we have ```validation.String("abcd").Reqired()``` much simpler. – usr784638 Jan 26 '19 at 05:35
  • How can we actually accept any type not only string in this example? – usr784638 Jan 27 '19 at 03:20
  • @usr784638 if it is treating for the zero value of any field then you could do that via reflection like this question https://www.google.com/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/13901819/quick-way-to-detect-empty-values-via-reflection-in-go&ved=2ahUKEwjZ94L1pY3gAhUytHEKHYPsDecQjjgwAHoECAcQAQ&usg=AOvVaw3pMO8hlP8Z5DP8YJIEYu48 – Iain Duncan Jan 27 '19 at 06:09