/**
@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
}