Skip to content
Discussion options

You must be logged in to vote

Commit V 0.4.12 7801f5b solves this question for an encoder. For a decoder is a little bit different.
https://play.vlang.io/p/926e017e92

struct Foo {
	a int // single field on purpose
}

fn encode[T](t T) string {
	$if T is $pointer{
		if voidptr(t) == unsafe{nil} {
			return 'null'
		} else {
			$for field in T.fields {
				val := t.$(field.name)
				return '&struct ${field.name}=${val}'
			}
		}
	} $else $if T is $struct {
		$for field in T.fields {
			val := t.$(field.name)
			return 'struct ${field.name}=${val}'
		}
	}
	return '?'
}

fn main() {
	assert encode(&Foo(unsafe{nil})) == 'null'
	obj := Foo{ a:1 }
	assert encode(obj) == 'struct a=1'
	assert encode(&obj) == '&struct a=1'
	ref :=

Replies: 3 comments 3 replies

Comment options

You must be logged in to vote
3 replies
@jorgeluismireles
Comment options

@jorgeluismireles
Comment options

@jorgeluismireles
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by jorgeluismireles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants