Last active
March 2, 2026 11:34
-
-
Save malikbenkirane/4cb15a43b71e7dc7c243564947c7a86a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "strconv" | |
| ) | |
| // An interface lets you avoid dealing directly with concrete types. | |
| type i0 interface { | |
| plus1() int | |
| } | |
| var _ i0 = a(0) // assign a value of type a to interface type t0 | |
| var _ i0 = b("hi") | |
| type a int | |
| type b string | |
| type s struct { | |
| x a | |
| y b | |
| } | |
| type c i0 | |
| // we implement func plus1 on type a | |
| // plus1 T= func(a) int | |
| // x.plus1 => plus1(x) | |
| // method: function on a value of a given type | |
| func (x a) plus1() int { | |
| return int(x) + 1 | |
| } | |
| // func f(x b, ....) | |
| // x = "hi" returns "hihi" | |
| func (x b) double() string { | |
| return string(x) + string(x) | |
| } | |
| func (x b) plus1() int { | |
| n, err := strconv.Atoi(string(x)) | |
| if err != nil { | |
| return 0 | |
| } | |
| return n + 1 | |
| } | |
| type p *int | |
| // func (x p) f() {} // receiver of type pointer not allowed | |
| // func (x i0) f() {} // receiver of type interface not allowed | |
| // y0 | |
| // f(x *a) [2 ] | |
| // | |
| // x0 x1 x2 | |
| // [y0 ][ ][ ] | |
| // *x = 2 | |
| func (x a) f() a { // immutable approach | |
| return a(2) | |
| } | |
| func (x *a) g() { // mutable approach | |
| *x = 2 | |
| } | |
| func main() { | |
| var i a = 3 | |
| v := a(1) // build value of type a with value of type int | |
| u := b("hi") | |
| var w = s{x: v, y: u} | |
| fmt.Println(u.double()) // "hihi" | |
| fmt.Println(v.plus1()) // 2 | |
| fmt.Println(i.plus1()) // 2 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment