如何将自定义类型转换为字符串?

时间:2015-08-29 05:10:48

标签: go

我使用的是套餐,而不是返回string,而是返回economy.ClassId您可以看到here

我想传递economy.ClassId,这只是一串数字,如" 531569319"对于一个不是economy.ClassId的字符串的函数,有没有办法将这种类型转换为字符串或否。感谢。

我知道您可能会喜欢strconv.FormatUint(),但我会将其用于自定义类型。

3 个答案:

答案 0 :(得分:6)

更一般地说,您可以在类型https://golang.org/pkg/fmt/#Stringer

上实施纵梁界面
func (c ClassId) String() string {
    return strconv.FormatUint(uint64(c),10)
}

并使用otherFunc(classId.String())

http://play.golang.org/p/cgdQZNR8GF

PS:也是首字母缩写词(ID)应该是所有首都

http://talks.golang.org/2014/names.slide#6

答案 1 :(得分:5)

- (IBAction)moveDownButtonClicked:(id)sender { _sliderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width , 0)]; [self.view.window addSubview: _sliderView]; [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:1.0]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; _sliderView.frame = CGRectMake(0,0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height*0.5); [UIView commitAnimations]; } 被声明为ClassId,因此虽然type ClassId uint64ClassId完全相同,但它们具有相同的基础类型,因此您可以从一个转换为另一个。要将值uint64转换为x类型(如果允许),请编写T。所以,在你的情况下:

T(x)

答案 2 :(得分:0)

另一种可能更惯用的方法是使用Go fmt.Sprintf使用format string specification

两个例子......

以下内容将classId转换为字符串基数10:

classIDStr := fmt.Sprintf("%d", classId)

以下内容将其转换为字符串十六进制数字,其中a-f数字为小写:

classIDHex := fmt.Sprintf("%x", classId)

相关问题