Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Method on a non-struct type in Go (Golang)

Posted on June 20, 2023June 20, 2023 by admin

Methods can also be defined on a non-struct custom type. Non-struct custom types can be created through type definition. Below is the format for creating a new custom type

type {type_name} {built_in_type}

For example we can a named custom type myFloat of type float64

type myFloat float64

Methods can be defined on the named custom type. See below example:

Code

package main
import (
"fmt"
"math"
)
type myFloat float64
func (m myFloat) ceil() float64 {
return math.Ceil(float64(m))
}
func main() {
num := myFloat(1.4)
fmt.Println(num.ceil())
}

Output

2
  • go
  • golang
  • method
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP