Skip to content

Instantly share code, notes, and snippets.

@tenntenn
Last active July 26, 2019 16:44
Show Gist options
  • Save tenntenn/c83df6c9d971156493a944cda8144f94 to your computer and use it in GitHub Desktop.
Save tenntenn/c83df6c9d971156493a944cda8144f94 to your computer and use it in GitHub Desktop.

Contract Tricks

contract ptr(t T) {
    *t
}

type Ptr struct {
    v reflect.Value
}

func PointerOf(type P ptr) (v P) Ptr {
    return Ptr{v: reflect.ValueOf(v)}
}

func (p Ptr) Elem() reflect.Value {
    return p.v.Elem()
}

Method

contract Stringer(t T) {
    // It includes fields
    t.String()
}
contract Stringer(t T) {
    // Only method
    var _ interface{
        String() string
    } = t
}

Field

contract Field(t T) {
   // It includes method
    t.Foo
}

A method cannot assign into variable.

contract Field(t T) {
    t.Foo = t.Foo
}

Interface

Type assertion allows only interface types.

contract Interface (_ T) {
    T.(struct{})
}

Array

len accepts pointers but only array's one.

contract Array(_ T) {
    len(&T{})
}

Slice

append accecpts only slices.

contract Slice(t T) {
    append(t, t...)
}

Map

delete accepts only maps and key can get from for range.

contract Map(t T) {
    for k, _ := range t {
        delete(t, k)
    }
}

Recivable channel

Just try to receive.

contract Receivable(t T) {
    <-t
}

Sendable channel

close accepts only sendable channel.

contract Sendable(t T) {
    close(t)
}

Pointer

Operator * accepts only poointers.

contract Pointer(t T) {
    *t
}

Named type

contract NamedType(_ T) {
    var _ struct {
        T
    }
}

T1 and T2 are different types

contract NeqT1T2(_ T1, _ T2) {
    var _ struct {
        T1
        T2
    }
}

Named type but not builtin types

contract NotBuiltin(_ T) {
    var _ struct {
        int;int8;int16;int32;int64
        uint;uint8;uint16;uint32;uint64
        uintptr;byte;rune
        float32;float64
        complex64;complex128
        string
        bool
        error
        T
    }
}

It does not accept any types

contract Deprecated(t T) {
   type D struct{}
   var _ D = t
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment