Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

but is it cleanly?

BTW, accessing common fields is temporarily disabled before releasing Go 1.18, because there is another fundamental problem which needs to be resolved firstly.

ref: https://github.com/golang/go/issues/51259



Right. It’s definitely not “clean” IMO.


Which other language has interfaces specifying field access, that does not go through indirect method call anyway? I guess if you consider C++ templates to be interfaces, that would apply, but C++ templates are even less clean (given that there isn’t even any clean way to specify interface expected by C++ template, all you have is type traits, which are opposite of clean).


> given that there isn’t even any clean way to specify interface expected by C++ template, all you have is type traits

Concepts?


Ah, sorry, I was not up to speed with C++, it’s called concepts now.

So, how do I specify, using concepts, that my template expects a type which has a field “.foo” of type int?


  template<typename T>
  concept has_foo = requires(T x){
  { x.foo } -> std::same_as<int>;
  };

  template<has_foo T>
  int get_foo(T x){...}

  // or

  template<typename T>
  requires has_foo<T>
  void f(T x){...}

  // or even

  void f(has_foo auto x) {...}


Does the above provide more safety/guarantees/something than just:

type hasFoo interface {

  getfoo() int

  setfoo(int)
}

func f(hasFoo) {}

?


The equivalent Go would be something like:

    func f[T interface{.Foo}](T) {}
Of course, this doesn't exist in Go, so we must do:

    func f[T interface{GetFoo(); SetFoo()}](T) {}
And then define setters and getters on every type we want to use, including defining new types (with the commensurate setters/getters) for types that we don't own (i.e., if you import a struct from another package and it doesn't have setters and getters defined, you have to create a new type that implements those setters/getters).


I don’t know Go, but I think less in that concepts are syntax guarantees, not semantic guarantees. I suspect interfaces (assuming they are opt-in) are semantic guarantees. That said, I’ve never run into this distinction being a problem, and you could provide opt-in mechanisms in C++. Of course, the C++ interface has zero runtime cost.


Unsure what's going on under the hood but C# allows access to fields transparently to the caller. One of the nicer features of the language.

  foo.baz = 1;        // baz could be a int or could be a setter.
  int baz = foo.baz;  // same




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: