在不获取包名称或指针的情况下获取Struct名称

时间:2019-10-30 16:25:10

标签: go

我有一个非常简单的代码,如下所示:

package chain_of_responsibility

import (
    "fmt"
    "reflect"
)

type CustomerBalanceRequest struct{
    CustomerName string
    Balance int
}

type BalanceRequest interface {
    Handle(request CustomerBalanceRequest)
}

type HeadEditor struct{
    Next BalanceRequest
}

func (h *HeadEditor) Handle(b CustomerBalanceRequest){
    if b.Balance < 1000 {
        fmt.Printf("%T approved balance for %v request. Balance: %v\n", h, b.CustomerName, b.Balance)
        fmt.Printf("%v approved balance for %v request. Balance: %v\n", reflect.TypeOf(h), b.CustomerName, b.Balance)
        fmt.Printf("%v approved balance for %v request. Balance: %v\n", reflect.TypeOf(h).String(), b.CustomerName, b.Balance)
        fmt.Printf("%v approved balance for %v request. Balance: %v\n", reflect.TypeOf(h).Name(), b.CustomerName, b.Balance)

    } else{
        h.Next.Handle(b)
    }
}

在fmt.Printf行上,我要打印HeadEditor类型的名称。我用各种方法来做到这一点,这就是我的结果:

*chain_of_responsibility.HeadEditor approved balance for John request. Balance: 500
*chain_of_responsibility.HeadEditor approved balance for John request. Balance: 500
*chain_of_responsibility.HeadEditor approved balance for John request. Balance: 500
 approved balance for John request. Balance: 500

问题出在前3个Printf调用上,我可以获得类型的名称,但是它们包括指针和包名称。有什么办法可以让我只获得“ HeadEditor”而没有包名称和指针,当然还有从结果中删除*和包名称之类的字符串处理解决方案。

1 个答案:

答案 0 :(得分:4)

您将与最后一个紧密联系。正如ORA-00001: unique constraint (RWMES.TB_TRIM_PATTERN_SET_POS_UK) violated 的文档所述:

Name()

您将返回空字符串,因为尽管// Name returns the type's name within its package for a defined type. // For other (non-defined) types it returns the empty string. 是定义的类型,但chain_of_responsibility.HeadEditor不是。您可以使用*chain_of_responsibility.HeadEditor从指针类型中获取类型:

Elem()

因此,如果并非总是要使用指针,则需要在调用// Elem returns a type's element type. // It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice. 之前先检查它是否是指针。

或者您可以通过基于反射并为您的类型提供一个返回要用于每种类型的字符串的方法来简化代码(可能更快),例如Elem()。然后,您可以定义一个Type() string接口来封装该方法。