Skip to content

Instantly share code, notes, and snippets.

@gxcsoccer
Created October 15, 2012 17:35
Show Gist options
  • Save gxcsoccer/3893867 to your computer and use it in GitHub Desktop.
Save gxcsoccer/3893867 to your computer and use it in GitHub Desktop.
删除数组中某一个元素,并返回删除的元素地址
package library
import (
"errors"
"fmt"
)
type MusicEntry struct {
Id string
Name string
Artist string
Source string
Type string
}
type MusicManager struct {
musics []MusicEntry
}
func NewMusicManager() *MusicManager {
return &MusicManager{make([]MusicEntry, 0)}
}
func (m *MusicManager) Len() int {
return len(m.musics)
}
func (m *MusicManager) Remove(index int) *MusicEntry {
if index < 0 || index >= len(m.musics) {
return nil
}
removeMusic := &m.musics[index] // 修改为removeMusic := m.musics[index],下面return &removeMusic就没有问题
fmt.Println("RemoveMusic.Id:", removeMusic.Id) // 输出 2
if index == 0 {
m.musics = m.musics[1:]
} else if index == len(m.musics)-1 {
m.musics = m.musics[:index]
} else {
m.musics = append(m.musics[:index], m.musics[index+1:]...)
}
fmt.Println("RemoveMusic.Id:", removeMusic.Id) // 输出 3
return removeMusic
}
func (m *MusicManager) Add(music *MusicEntry) {
m.musics = append(m.musics, *music)
}
package library
import (
"fmt"
"testing"
)
func TestOps(t *testing.T) {
mm := NewMusicManager()
if mm == nil {
t.Error("NewMusicManager failed")
}
if mm.Len() != 0 {
t.Error("NewMusicManager failed, not empty")
}
m0 := &MusicEntry{"1", "My heart will go on", "Celion Dion", "http://qbox/12321321", "mp3"}
m1 := &MusicEntry{"2", "In Your Arms", "Stanfour", "http://qbox/221313", "wav"}
m2 := &MusicEntry{"3", "Love", "Peter", "http://qbox/123", "mp3"}
mm.Add(m0)
mm.Add(m1)
mm.Add(m2)
if mm.Len() != 3 {
t.Error("MusicManager.Add() failed")
}
mRemoved := mm.Remove(1)
if mm.Len() != 2 {
t.Error("MusicManager.Remove() failed")
}
if mRemoved == nil || mRemoved.Id != m1.Id {
t.Error("MusicManager.Remove() failed") // 此处报错
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment