0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Go 言語 interface 使い方のおぼえがき

Last updated at Posted at 2023-09-02
package main

import (
    "fmt"
)

type IF interface {
    setter(any)
    getter() (any)
}

type struct_aaa struct {
    prop   string ;
}

type struct_bbb struct {
    prop   int ;
}

func (ctx *struct_aaa) setter(arg any){
    ctx.prop = arg.(string) ;
}

func (ctx *struct_aaa) getter() (any){
    return ctx.prop ;
}

func (ctx *struct_bbb) setter(arg any){
    ctx.prop = arg.(int) ;
}

func (ctx *struct_bbb) getter() (any){
    return ctx.prop ;
}

func set(i IF,v any){
    i.setter(v) ;
}

func get(i IF) (any){
    return i.getter() ;
}

func case_01(){
    fmt.Printf("case_01\n") ;
    var a struct_aaa ;
    var b struct_bbb ;

    var if_a IF = &a ;
    var if_b IF = &b ;

    set(&a,"ABC")
    set(&b,123)

    fmt.Printf("A-1-1[%V]\n",a.prop) ;
    fmt.Printf("B-1-1[%V]\n",b.prop) ;

    fmt.Printf("A-1-2[%V]\n",get(&a)) ;
    fmt.Printf("B-1-2[%V]\n",get(&b)) ;

    fmt.Printf("A-1-3[%V]\n",if_a.getter()) ;
    fmt.Printf("B-1-3[%V]\n",if_b.getter()) ;
}

func case_02(){
    fmt.Printf("case_02\n") ;
    var if_a IF = &struct_aaa{} ;
    var if_b IF = &struct_bbb{} ;

    if_a.setter("xyz") ;
    if_b.setter(222) ;

    fmt.Printf("A-2[%V]\n",if_a.getter()) ;
    fmt.Printf("B-2[%V]\n",if_b.getter()) ;
}

func case_03(){

    fmt.Printf("case_03\n") ;

    var if_a IF = &struct_aaa{"ppp"} ;
    var if_b IF = &struct_bbb{333} ;

    fmt.Printf("A-3[%V]\n",if_a.getter()) ;
    fmt.Printf("B-3[%V]\n",if_b.getter()) ;
}

func main(){

    case_01() ;
    case_02() ;
    case_03() ;

    fmt.Printf("Done.\n") ;
}

実行結果

case_01
A-1-1[%!V(string=ABC)]
B-1-1[%!V(int=123)]
A-1-2[%!V(string=ABC)]
B-1-2[%!V(int=123)]
A-1-3[%!V(string=ABC)]
B-1-3[%!V(int=123)]
case_02
A-2[%!V(string=xyz)]
B-2[%!V(int=222)]
case_03
A-3[%!V(string=ppp)]
B-3[%!V(int=333)]
Done.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?