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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失