Custom attributes syntax discussion #23445
Replies: 5 comments 9 replies
-
I much prefer the simplicity of the C# version, although it should be expanded at least slightly. For example, it would be good to be able to specify the number and type of arguments. I'm not sure what good versioning will do on an attribute, although it might be handy for future-proofing, in case we needed to change how the attribute worked, the number and type of arguments, etc. |
Beta Was this translation helpful? Give feedback.
-
I like the struct proposal seen here: #11732 Basically, something like this: @[attribute]
struct SomeAttr {
// mut not allowed. in the original post, it was pub by default. However IMO we should not do that because we are using plain struts here. I would rather use existing syntax than changing it.
pub:
name string
age int
}
@[SomeAttr{"Gandalf", 50000}]
fn something () { ... } I also think we should pull from Java a little bit by giving attributes a list of which things they can be applied to, maybe something like this: @[attribute: 'fn'; attribute: 'struct']
struct MyAttribute { ... }
// This would produce a compiler error:
struct Hello {
name string @[MyAttribute{}]
} Edit: For attribute that are hard coded (inline, extern, attribute, etc), we can probably leave them as is. Structs mandate CamelCase and all existing attributes are lower_snake_case, giving a clear distinction. Migrating fully to one single syntax would certainly be nicer in my opinion, but that is a topic for later I think. |
Beta Was this translation helpful? Give feedback.
-
@EmmaTheMartian sounds good to me. |
Beta Was this translation helpful? Give feedback.
-
An alternative is to borrow Go tags simple map syntax but combined with already form package main
import (
"fmt"
"reflect"
)
func main() {
type S struct {
F string `species:"gopher" color:"blue"`
}
s := S{}
st := reflect.TypeOf(s)
field := st.Field(0)
fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
} Useful in json encoding and read by a reflection package. And very important to document the whole mechanism: https://pkg.go.dev/reflect#StructTag |
Beta Was this translation helpful? Give feedback.
-
Has this started yet? What is the final grammar? |
Beta Was this translation helpful? Give feedback.
-
For general ideas:
C#
Python
Swift
Beta Was this translation helpful? Give feedback.
All reactions