可能的重复:
从对象中删除项目
我有一个像下面这样的对象:
questions = new Object();
questions = {
"q1":"answer1",
"q2":"answer2",
"q3":"answer3",
"q4":"answer4"
}
Run Code Online (Sandbox Code Playgroud)
如何删除 q3 和 q4 并仍然保留 q1 和 q1?请尽可能提出动态方法,因为问题对象是动态填充的,并且可能有不同数量的项目。
我尝试使用 .slice 没有运气:
question = "q2";
questions = questions.slice(0, question);
Run Code Online (Sandbox Code Playgroud) type student struct {
Name string
Age int
}
func main() {
m := make(map[string]*student)
s := []student{
{Name: "Allen", Age: 24},
{Name: "Tom", Age: 23},
}
for _, stu := range s {
m[stu.Name] = &stu
}
fmt.Println(m)
for key, value := range m {
fmt.Println(key, value)
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
地图[艾伦:0xc42006a0c0 汤姆:0xc42006a0c0]
艾伦和{汤姆 23}
汤姆 &{汤姆 23}
如何解释Slice的现象,在我看来,stu应该是s的每个成员的地址,但是从结果来看,s的地址是相同的。
我知道我可以用字符串填充 Go 切片strings := []string{"something", "something else"},但是除了接口之外我怎么能做同样的事情呢?我尝试了以下方法:
data := []interface{}{{ID: "123"}, {ID: "456"}}
Run Code Online (Sandbox Code Playgroud)
并得到以下错误:
missing type in composite literal
Run Code Online (Sandbox Code Playgroud)
我也尝试使用这样的结构:
type Users struct {
ID string
}
[]Users{{ID: "123"}, {ID: "456"}}
Run Code Online (Sandbox Code Playgroud)
哪个有效,但是mongo的InsertMany函数需要一个[]interface{}参数:
cannot use users (type []Users) as type []interface {} in argument to database.InsertMany
Run Code Online (Sandbox Code Playgroud)
我如何定义和填充一个[]interface{}?
在下面的代码中:
type ProductEntity struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Price float32 `json:"price"`
SKU string `json:"sku"`
CreatedOn string `json:"-"`
UpdatedOn string `json:"-"`
DeletedOn string `json:"-"`
}
type ProductEntityList []*ProductEntity
type PostRequestModel struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Price float32 `json:"price"`
SKU string `json:"sku"`
CreatedOn string `json:"-"`
UpdatedOn string `json:"-"`
DeletedOn string `json:"-"`
}
type RequestBody []*PostRequestModel
func convertModelToEntity(modelList RequestBody) ProductEntityList {
// return entity.ProductEntityList(modelList) // type conversion error
}
Run Code Online (Sandbox Code Playgroud)
如何将数据从一种类型复制到另一种具有相同结构的类型?因为RequestBody …
package main
import "fmt"
func main() {
arr := make([]int,3,4)
fmt.Println(fmt.Sprintf("before len:%d,cap:%d, address:%p",len(arr), cap(arr), &arr))
arr = arr[1:2]
fmt.Println(fmt.Sprintf("after len:%d,cap:%d, address:%p",len(arr), cap(arr), &arr))
}
Run Code Online (Sandbox Code Playgroud)
before len:3,cap:4, address:0xc0000a6020
after len:1,cap:3, address:0xc0000a6020
Run Code Online (Sandbox Code Playgroud)
切片前后的地址是一样的。
我的问题是,当它的 len 从 3 更改为 1 时,切片是否会分配新的内存。
因为 slice 有三个元素, Data uintptr, Len int, Cap int 如果其中一个发生变化,我的猜测是内存上会生成一个新的 slice,是真的吗?
我想初始化一个长度为 3 的空整数切片,在切片中存储随机整数,并在每次迭代时对切片进行排序。这段代码实现了:
package main
import (
"fmt"
"math/rand"
"sort"
)
func main() {
myslice := make([]int, 3)
for i := 0; i < 10; i++ {
myslice = append(myslice, rand.Intn(100))
sort.IntSlice(myslice).Sort()
fmt.Println(myslice)
}
}
Run Code Online (Sandbox Code Playgroud)
最终结果:[0 0 0 5 23 28 43 45 50 57 68 76 87]但是,我还想在追加新元素之前覆盖初始元素(换句话说,去掉那些零)。由于切片在每次迭代时都进行了排序,因此调用myslice[i] = rand.Intn(100)ifi < 3不一定有效。
我最初的解决方案是编写一个函数来获取 0 的第一个索引i < 3,并用新的随机值替换该索引......但是,我想知道是否有更好的选择来覆盖切片的初始值。
我正在为学校做一个回文检查计划,但有一个转折点.
现在我已经知道我可以使用反向函数或类似的东西:
[-1::-1]
Run Code Online (Sandbox Code Playgroud)
但是,该程序特别要求不进行字符串切片或使用.reverse()函数.所以,我的问题是,如果我不能使用这两个简单的方法,我将如何做到这一点?
append()当给定切片的容量不足时,Go的功能仅分配新的切片数据(另请参阅:https://stackoverflow.com/a/28143457/802833).这可能导致意外行为(至少对我来说是一个golang新手):
package main
import (
"fmt"
)
func main() {
a1 := make([][]int, 3)
a2 := make([][]int, 3)
b := [][]int{{1, 1, 1}, {2, 2, 2}, {3, 3, 3}}
common1 := make([]int, 0)
common2 := make([]int, 0, 12) // provide sufficient capacity
common1 = append(common1, []int{10, 20}...)
common2 = append(common2, []int{10, 20}...)
idx := 0
for _, k := range b {
a1[idx] = append(common1, k...) // new slice is allocated
a2[idx] = append(common2, k...) …Run Code Online (Sandbox Code Playgroud) 我有以下代码
package main
import "fmt"
func main() {
a := []int{1}
b := &a[0]
fmt.Println(a, &a[0], b, *b) // prints [1] 0xc00001c030 0xc00001c030 1
a = append(a, 1, 2, 3)
fmt.Println(a, &a[0], b, *b) // prints [1 1 2 3] 0xc000100020 0xc00001c030 1
}
Run Code Online (Sandbox Code Playgroud)
首先它创建一个 1 int 的切片。它的 len 是 1,cap 也是 1。然后我获取一个指向它的第一个元素的指针,并在 print 中获取底层指针值。正如预期的那样,它工作得很好。
然后我向切片中添加 3 个元素,从而扩展切片的容量,从而将其复制到内存中的另一个位置。之后,我打印切片第一个元素的地址(通过获取指针),该地址现在与存储在b.
但是,当我打印它的基本值时,它b也可以正常工作。我不明白为什么它有效。据我所知,第一个元素指向的切片b已复制到内存中的另一个位置,因此它之前的内存肯定已被释放。然而,它似乎仍然存在。
如果我们查看映射,golang 甚至不允许我们通过键在元素上创建指针,因为完全相同的问题 - 底层数据可以移动到内存中的另一个位置。然而,它对于切片来说效果非常好。为什么会这样呢?它到底是如何运作的?内存没有被释放是因为仍然有一个变量指向该内存吗?它与地图有何不同?
我已将问题作为注释包含在代码中。
我在这里看到不一致的地方。我们在这里做三片。在第一个切片s = s [:0]之后,s应该始终指向s [:0]。
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
//1
s = s[:0]
printSlice(s) //after we do this, should not the var s always point to s[:0]?
// Extend its length.
s = s[:4]
printSlice(s) //here, how is this s pointing back to original s? we just changed it to be s = s[:0]
// Drop …Run Code Online (Sandbox Code Playgroud) 拆分字符串时,使用strings.Split,如果输入字符串为空,则生成的空切片的长度为 1。
package main
import (
"strings"
"fmt"
)
func main() {
emptySlice1 := []string{}
debugSlice( emptySlice1 ) // prints "[], []string, len 0"
someStringToSplit := ""
emptySlice2 := strings.Split(someStringToSplit , " ")
debugSlice( emptySlice2 ) // prints "[], []string, len 1"
}
func debugSlice( s []string ){
fmt.Printf("%v, %T, len %v\n", s, s, len(s))
}
Run Code Online (Sandbox Code Playgroud)
游乐场可以在这里找到:https : //play.golang.org/p/kBYR048UtP_0
这是为什么?如何检查切片内的实际项目数(如果没有len功能)?
我有两个这样的嵌套结构:
type Block struct {
ID string
Contents []string
}
type Package struct {
Name string
Blocks []Block
}
Run Code Online (Sandbox Code Playgroud)
p当我尝试在特定块中附加新内容时,原始包 ( ) 不会更改。
for _, b := range p.Blocks {
if b.ID == "B1" {
fmt.Println("Adding a new content")
b.Contents = append(b.Contents, "c3")
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
在Go中,我想在整数数组中找到最后一个元素。
我有一个清单:
[0.0.1, 0.0.2, 0.0.3]
Run Code Online (Sandbox Code Playgroud)
我只是想:
0.0.3
Run Code Online (Sandbox Code Playgroud)
每次我尝试返回最后一个元素时,控制台都会返回
%!(EXTRA uint8=10)
Run Code Online (Sandbox Code Playgroud)
我认为这意味着我需要将字节数组转换为切片?
这是我的代码:
[0.0.1, 0.0.2, 0.0.3]
Run Code Online (Sandbox Code Playgroud)
这是输出:
Variable Type:
[]uint8
Variable:
0.0.1
0.0.2
0.0.3
release version:%!(EXTRA uint8=10)
Run Code Online (Sandbox Code Playgroud)