MST

星途 面试题库

面试题:Go中如何基于自定义类型扩展方法

在Go语言中,定义一个自定义类型 `MyInt` 为 `int` 类型,然后为 `MyInt` 扩展一个方法 `Double`,该方法返回 `MyInt` 值的两倍。请写出完整代码。
46.1万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import "fmt"

// 定义自定义类型MyInt
type MyInt int

// 为MyInt扩展Double方法
func (m MyInt) Double() MyInt {
    return m * 2
}

你可以使用如下方式调用这个方法:

func main() {
    var num MyInt = 5
    result := num.Double()
    fmt.Println(result) 
}