Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create methods for string type in Golang

Tags:

go

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.

like image 841
usr784638 Avatar asked Jan 24 '19 13:01

usr784638


1 Answers

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

like image 182
Iain Duncan Avatar answered Sep 22 '22 06:09

Iain Duncan