Creating an Array
Java
DVD[] dvdCollection = new DVD[15];
public class DVD {
public String name;
public int releaseYear;
public String director;
public DVD(String name, int releaseYear, String director) {
this.name = name;
this.releaseYear = releaseYear;
this.director = director;
}
public String toString() {
return this.name + ", directed by " + this.director + ", released in " + this.releaseYear;
}
}
Go
var dvdCollection = [15]DVD{}
type DVD struct {
name string
releaseYear int
director string
}
func (d *DVD) AddDVD(name string, releaseYear int, director string) {
d.name = name
d.releaseYear = releaseYear
d.director = director
}
func (d DVD) String() string {
if d.name != "" {
s := fmt.Sprintf("%s, directed by %s, released in %d", d.name, d.director, d.releaseYear)
return s
}
return "null"
}
- I don't think AddDVD function is needed in Go. because I can decalre values in structure without it.
Writing Items into an Array
Java
DVD avengersDVD = new DVD("The Avengers", 2012, "Joss Whedon");
dvdCollection[7] = avengersDVD;
Go
avengersDVD := DVD{"The Avengers", 2012, "Joss Whedon"}
dvdCollection[7] = avengersDVD
Java
DVD incrediblesDVD = new DVD("The Incredibles", 2004, "Brad Bird");
DVD findingDoryDVD = new DVD("Finding Dory", 2016, "Andrew Stanton");
DVD lionKingDVD = new DVD("The Lion King", 2019, "Jon Favreau");
dvdCollection[3] = incrediblesDVD;
dvdCollection[9] = findingDoryDVD;
dvdCollection[2] = lionKingDVD;
Go
incrediblesDVD := DVD{"The Incredibles", 2004, "Brad Bird"}
findingDoryDVD := DVD{"Finding Dory", 2016, "Andrew Stanton"}
lionKingDVD := DVD{"The Lion King", 2019, "Jon Favreau"}
dvdCollection[3] = incrediblesDVD
dvdCollection[9] = findingDoryDVD
dvdCollection[2] = lionKingDVD
Java
DVD starWarsDVD = new DVD("Star Wars", 1977, "George Lucas");
dvdCollection[3] = starWarsDVD;
Go
starWarsDVD := DVD{"Star Wars", 1977, "George Lucas"}
dvdCollection[3] = starWarsDVD
Reading Items from an Array
Java
System.out.println(dvdCollection[7]);
System.out.println(dvdCollection[10]);
System.out.println(dvdCollection[3]);
Go
fmt.Println(dvdCollection[7])
fmt.Println(dvdCollection[10])
fmt.Println(dvdCollection[3])
- go.dev/play/p/K9DPj7RxrXV