Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: Go 2: extend contracts to include member variables #33408

Open
jfcg opened this issue Aug 1, 2019 · 1 comment

Comments

@jfcg
Copy link

commented Aug 1, 2019

Contracts proposal includes only member functions.

contract stringer(T) {
	T String() string
}

this means "type T shall have a method named String that returns string". A natural extension could be like:

contract sortable(S) {
	S Key int
}

sortable contract means "type S shall have a member named Key that is int". A better extension could be:

contract ordered(T) {
	T int, int8, int16, int32, int64, uint, uint8, uint16,
		uint32, uint64, uintptr, float32, float64, string
}

contract sortable2(S, T) {
	ordered(T)
	S Key T
}

sortable2 contract means "type S shall have a member named Key that is ordered". This contract could be used like:

func Sort(type S sortable2) (x []S) {
	...
	if x[i].Key < x[j].Key {
		...
	}
	...
}

Also I think this syntax is better for methods and members:

contract stringer(T) {
	T.String() string
}

contract sortable(S) {
	S.Key int
}

A further extension could be like:

type Person struct {
	Name string
	Age int
}

Say, I would like to sort a []Person w.r.t Age somewhere in my app, and w.r.t. Name at some other place in my app. I dont even want to dictate a member name "Key" to the user of my Sort() function. So I want to:

contract orderedMember(S, M) {
	ordered(S.M)
}
// or
contract orderedMember(S, M, T) {
	ordered(T)
	S.M T
}

this contract means "type S has a member M that is ordered". So that could be used like:

func Sort(type S orderedMember) (x []S){
...
	if x[i].M < x[j].M { // use M in code
...
}

var x []Person
...
Sort(M=Age) (x)
Sort(M=Name) (x)

@gopherbot gopherbot added this to the Proposal milestone Aug 1, 2019

@gopherbot gopherbot added the Proposal label Aug 1, 2019

@ianlancetaylor ianlancetaylor changed the title Proposal: Go 2: Extend contracts to include member variables proposal: Go 2: extend contracts to include member variables Aug 1, 2019

@ianlancetaylor

This comment has been minimized.

Copy link
Contributor

commented Aug 1, 2019

There are many ways we could extend the design draft. Let's start by seeing whether it works at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants
You can’t perform that action at this time.