manager.go
/**
@author CuiZhouwei
@date 2022/7/28
**/
package library
import (
"errors"
"fmt"
)
type Music struct {
Id string
Name string
Artist string
Source string
Type string
}
type MusicManager struct {
musics []Music
}
func NewMusicManager() *MusicManager {
return &MusicManager{
musics: make([]Music, 0),
}
}
func (m *MusicManager) Len() int {
return len(m.musics)
}
func (m *MusicManager) Get(index int) (music *Music, err error) {
if index < 0 || index >= len(m.musics) {
return nil, errors.New("index out of range ")
}
return &m.musics[index], nil
}
func (m *MusicManager) Find(name string) (int, *Music) {
if len(m.musics) == 0 {
return 0, nil
}
for k, music := range m.musics {
if music.Name == name {
return k, &music
}
}
return 0, nil
}
func (m *MusicManager) Add(music *Music) {
m.musics = append(m.musics, *music)
}
func (m *MusicManager) Remove(index int) *Music {
if index < 0 || index >= len(m.musics) {
fmt.Println("请重新选择删除的序号..")
return nil
}
removeMusic := &m.musics[index]
fmt.Printf("remove %s music already\n", removeMusic.Name)
if index < len(m.musics)-1 {
m.musics = append(m.musics[:index], m.musics[index+1:]...)
} else if index == 0 {
m.musics = m.musics[0:0] //make([]music,0)
} else {
m.musics = m.musics[:index]
}
return removeMusic
}
func (m *MusicManager) RemoveByName(name string) *Music {
if len(m.musics) == 0 {
return nil
}
index, music := m.Find(name)
if music == nil {
fmt.Printf("ths music %s did`t find", name)
}
m.Remove(index)
return nil
}
manager_test.go
/**
@author CuiZhouwei
@date 2022/7/29
**/
package library
import (
"testing"
)
func TestOps(t *testing.T) {
mm := NewMusicManager()
if mm == nil {
t.Error("NewMusicManager failed")
}
if mm.Len() != 0{
t.Error("NewMusicManager falied,not empty.")
}
m0 := &Music{
Id: "1",
Name: "Take me to you heart",
Artist: "Mike",
Source: "http://qbox.me/2450123",
Type: "MP3",
}
m1 := &Music{
Id: "1",
Name: "Take me to you heart",
Artist: "Mike",
Source: "http://qbox.me/2450123",
Type: "MP3",
}
mm.Add(m0)
mm.Add(m1)
if mm.Len() != 2{
t.Error("MusicManager.Add() failed.")
}
_,m := mm.Find(m0.Name)
if m== nil{
t.Error("MusicManager.Find().")
}
if m.Id != m0.Id||m.Artist != m0.Artist ||
m.Type != m0.Type || m.Name != m0.Name ||m.Source != m0.Source{
t.Error("MusicManager.Find() failed.Found item mismatch.")
}
m ,err:= mm.Get(0)
if m== nil {
t.Error("MusicManger.Get() failed.",err)
}
m = mm.Remove(0)
if m == nil || mm.Len() != 1 {
t.Error("musicmanager.Remove failed.",err)
}
m = mm.RemoveByName(m0.Name)
if m == nil || mm.Len() != 0 {
t.Error("musicmanager.Remove failed.",err)
}
}