FAQ
Add a method AllSubSystems() to House that returns a slice containing all ComputerSystems,
BiologicalSystems, PlumbingSystems. Then you can do this:

func (allSystems *AllSystems) AreGo() bool {
for _, system := range(AllSystems.AllSubSystems()) {
if !system.IsGo() {
return false
}
}
         return true;
}

For this to work make sure that ComputerSystem, BiologicalSystem, PlumbingSystem
implement a common interface with a function IsGo().


Am Mittwoch, 1. April 2015 13:42:12 UTC+2 schrieb Bayan Khalili:
I am trying to reduce the amount of code duplication where I iterate
through a number of slices of different types, but where the same method is
called for each type.
I've constructed a (much shorter and simpler) example to illustrate.

Assume we have the following types defined:

type ComputerSystem struct { ... }
type BiologicalSystem struct { ... }
type PlumbingSystem struct { ... }
type AllSystems struct {
ComputerSystems []*ComputerSystem
BiologicalSystems []*BiologicalSystem
PlumbingSystems []*PlumbingSystem
}


And each of the "System" types have an "IsGo" method defined with the same
arguments and return type. I.e.:

func (s *ComputerSystem) IsGo() bool { ... }
func (s *BiologicalSystem) IsGo() bool { ... }
func (s *PlumbingSystem) IsGo() bool { ... }

I have written a method that checks if an AllSystems instance returns
false for any of it's subsystems:

func (allSystems *AllSystems) AreGo() bool {
for _, system := range(allSystems.ComputerSystems) {
if !system.IsGo() {
return false
}
}
for _, system := range(allSystems.BiologicalSystems) {
if !system.IsGo() {
return false
}
}
for _, system := range(allSystems.PlumbingSystems) {
if !system.IsGo() {
return false
}
}
return true
}

The code includes an identical for loop for each sub system slice.

Is there a way to DRY this up?
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 33 of 37 | next ›
Discussion Overview
groupgolang-nuts @
categoriesgo
postedApr 1, '15 at 11:42a
activeApr 8, '15 at 3:07a
posts37
users13
websitegolang.org

People

Translate

site design / logo © 2022 Grokbase