For example I have two different structs Foo
and Bar
struct Foo {...}
struct Bar {...}
and a lot of functions and other types built on them.
C++ flavor:
template<typename T>
struct Identified {
T model;
std::string id;
};
template<typename T>
Identified<T> GetIdentifiedModel(std::string id) {
Identified<T> result;
T.id = id;
T.model.set(getSomeData(id)); // Common method for T
return result;
}
How to implement these examples in Go?
For common methods, interfaces do the job but I don't see how to retrieve a specific type from an interface to declare it, return it or anything else and I can't handle copy/paste code anymore :)
Thanks !
Edit @Amd: https://ideone.com/rqpsQb
#include <string>
#include <iostream>
struct Foo {
char c;
void set(std::string s) {c = s[0];}; // We don't really care here
};
struct Bar {
int n;
void set(std::string s) {n = s.size();}; // We don't really care here
};
template<typename T>
struct Identified {
T model;
std::string id;
};
template<typename T>
Identified<T> GetIdentifiedModel(std::string id) {
Identified<T> result;
result.id = id;
// Obviously shouldn't be ID but for the example
result.model.set(id); // Common method for T
return result;
}
void assert(bool b) {
if (b) std::cout << "OK" << std::endl;
else std::cout << "There is a problem !" << std::endl;
};
int main() {
auto fooWithID = GetIdentifiedModel<Foo>("foo id");
auto barWithID = GetIdentifiedModel<Bar>("bar");
assert (fooWithID.model.c == 'f');
assert (barWithID.model.n == 3);
return (0);
}