dongqian6484 2019-01-24 13:01
浏览 107
已采纳

如何在Golang中为字符串类型创建方法

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.

  • 写回答

1条回答 默认 最新

  • dregvw1801 2019-01-24 13:36
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 变数的长度不一样”。是什么原因呢?如何修改?
  • ¥15 matlab作业不会写
  • ¥15 eclipse mqtt 消息消费问题
  • ¥15 vue2(标签-chrome|关键词-浏览器兼容)
  • ¥15 python网络流自动生成系统 医学领域
  • ¥15 sql查询仓库里都有什么
  • ¥15 代码的修改,添加和运行完善
  • ¥15 krpano-场景分组和自定义地图分组
  • ¥15 lammps Gpu加速出错
  • ¥15 关于PLUS模型中kapaa值的问题