Is it possible to declare an interface with fields in Go, like in Java/C#?
Hi everyone! I'm new to Go, transitioning from Java. In Java, I'm used to interfaces containing not only method signatures but also fields (properties). For example:
```java
public interface Animal {
String name = "Unknown";
void speak();
}
```
Now I'm trying to do the same in Go:
```go
type Animal interface {
Name string
Speak()
}
```
The compiler gives an error: `interface contains embedded field Name which is not a method`. I'm confused. How do you properly describe a structure in Go that is guaranteed to contain certain fields? I need any object implementing the `Animal` interface to necessarily have a `Name` field (a string). Without this, my program breaks at compile time.
I tried doing this:
```go
type Animal struct {
Name string
```
No answers yet.
Log in to leave an answer