Sobes.tech
Junior — Middle

Is it possible to extend the functionality of standard packages by adding your own methods?

sobes.tech AI

Answer from AI

In Go, you cannot directly add methods to types from standard packages if these types are defined in another package. However, you can create your own types based on existing ones (using type alias or type newType) and add methods to the new types.

Example:

package main

import (
    "fmt"
    "strings"
)

type MyString string

func (s MyString) Reverse() string {
    runes := []rune(string(s))
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func main() {
    var s MyString = "hello"
    fmt.Println(s.Reverse()) // olleh
}

Thus, the functionality of standard types can be extended through wrappers, but not by adding methods directly to types from standard packages.

Is it possible to extend the functionality of… - sobes.tech