René's URL Explorer Experiment


Title: slice 的问题 · Issue #124 · codcodog/Blog · GitHub

Open Graph Title: slice 的问题 · Issue #124 · codcodog/Blog

X Title: slice 的问题 · Issue #124 · codcodog/Blog

Description: slice 的问题 场景 package main import "fmt" type cities []string func main() { Nepal := cities{"Kathmandu", "Pokhara", "Lumbini"} Nepal.add() Nepal.print() } func (c cities) print() { for i, city := range c { fmt.Println(i, city) } } func (c ...

Open Graph Description: slice 的问题 场景 package main import "fmt" type cities []string func main() { Nepal := cities{"Kathmandu", "Pokhara", "Lumbini"} Nepal.add() Nepal.print() } func (c cities) print() { for i, city := ran...

X Description: slice 的问题 场景 package main import "fmt" type cities []string func main() { Nepal := cities{"Kathmandu", "Pokhara", "Lumbini"} Nepal.add() Nepal.print() } func...

Opengraph URL: https://github.com/codcodog/Blog/issues/124

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"slice 的问题","articleBody":"slice 的问题\r\n=============\r\n\r\n### 场景\r\n\r\n```golang\r\npackage main\r\n\r\nimport \"fmt\"\r\n\r\ntype cities []string\r\n\r\nfunc main() {\r\n\tNepal := cities{\"Kathmandu\", \"Pokhara\", \"Lumbini\"}\r\n\tNepal.add()\r\n\tNepal.print()\r\n}\r\n\r\nfunc (c cities) print() {\r\n\tfor i, city := range c {\r\n\t\tfmt.Println(i, city)\r\n\t}\r\n}\r\n\r\nfunc (c cities) add() {\r\n\tc = append(c, \"hello\")\r\n}\r\n```\r\n\r\n执行输出如下:\r\n```\r\n0 Kathmandu\r\n1 Pokhara\r\n2 Lumbini\r\n```\r\n结果没有 `3 hello`\r\n\r\n### 原因\r\n\r\n`slice` 跟 `array` 很类似,但是它更灵活,可以自动扩容.  \r\n\r\n由源码可以看到它的本质:\r\n```\r\n// runtime/slice.go\r\ntype slice struct {\r\n\tarray unsafe.Pointer // 元素指针\r\n\tlen   int // 长度\r\n\tcap   int // 容量\r\n}\r\n```\r\n\r\n`slice` 有三个属性,分别是指向底层数组的指针,切片可用的元素个数,底层数组的元素个数.\r\n\u003e 底层的数组可能被多个 `slice` 指向,所以修改其中一个 `slice` 的时候,会因此影响到其他的 `slice`.\r\n\r\n上面的代码 `c = append(c, \"hello\")` 之后,遍历 `c` 却没有 `hello`,这主要涉及到 `slice` 的扩容问题.\r\n\r\n在添加元素的时候,如果 `slice` 的容量不够的时候,是会先读取原有元素,然后 cap 扩大一倍,再重新复制到新的数组中去,`slice` 的数组指针也更新为新的数组指针.\r\n\r\n把上面代码 `c` 的指针地址打印下,就清晰很多了.\r\n```golang\r\npackage main\r\n\r\nimport \"fmt\"\r\n\r\ntype cities []string\r\n\r\nfunc main() {\r\n\tNepal := cities{\"Kathmandu\", \"Pokhara\", \"Lumbini\"}\r\n\tNepal.add()\r\n\tNepal.print()\r\n}\r\n\r\nfunc (c cities) print() {\r\n\tfmt.Printf(\"print(): %p \\n\", c)\r\n\tfor i, city := range c {\r\n\t\tfmt.Println(i, city)\r\n\t}\r\n}\r\n\r\nfunc (c cities) add() {\r\n\tfmt.Printf(\"add() append before: %p \\n\", c)\r\n\tc = append(c, \"hello\")\r\n\tfmt.Printf(\"add() append after: %p \\n\", c)\r\n}\r\n```\r\n\r\n输出如下:\r\n```\r\nadd() append before: 0xc000070150 # append 前后地址不一样\r\nadd() append after: 0xc00007c120\r\nprint(): 0xc000070150\r\n0 Kathmandu\r\n1 Pokhara\r\n2 Lumbini\r\n```\r\n\r\n### 解决\r\n\r\n在 `add()` 方法的时候,使用指针赋值,直接修改原来的 `slice`.\r\n```golang\r\nfunc (c *cities) add() {\r\n\t*c = append(*c, \"hello\")\r\n}\r\n```\r\n\r\n输出如下:\r\n```\r\n0 Kathmandu\r\n1 Pokhara\r\n2 Lumbini\r\n3 hello\r\n```\r\n\r\n### 参考\r\n[how-to-append-to-a-slice-pointer-receiver](https://stackoverflow.com/questions/36854408/how-to-append-to-a-slice-pointer-receiver/36854446)  \r\n[深度解密Go语言之Slice](https://www.cnblogs.com/qcrao-2018/p/10631989.html)\r\n","author":{"url":"https://github.com/codcodog","@type":"Person","name":"codcodog"},"datePublished":"2020-10-28T14:02:47.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":0},"url":"https://github.com/124/Blog/issues/124"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:a249abaf-3c95-3f87-689a-957cb1626e1a
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idD59A:2630A2:1468AEF:1C6497B:6A4CB0CE
html-safe-nonce8c08621a01f25f1320c8abca8c3879fd8f5912f5076e62bf8b82ffa65588d405
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJENTlBOjI2MzBBMjoxNDY4QUVGOjFDNjQ5N0I6NkE0Q0IwQ0UiLCJ2aXNpdG9yX2lkIjoiMzg0NzY3OTM1NzY0OTQ2NTU1MCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac9c35a1d8015042e386a15c4f31b06de35ee0927a3f6156075472659c8dfdc030
hovercard-subject-tagissue:731471272
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/codcodog/Blog/124/issue_layout
twitter:imagehttps://opengraph.githubassets.com/6eca7330b5124c123a15c57f1eae90519b24a9a99e09ba01beffa2c62e8f0937/codcodog/Blog/issues/124
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/6eca7330b5124c123a15c57f1eae90519b24a9a99e09ba01beffa2c62e8f0937/codcodog/Blog/issues/124
og:image:altslice 的问题 场景 package main import "fmt" type cities []string func main() { Nepal := cities{"Kathmandu", "Pokhara", "Lumbini"} Nepal.add() Nepal.print() } func (c cities) print() { for i, city := ran...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamecodcodog
hostnamegithub.com
expected-hostnamegithub.com
None3d11bb817438277de2a940854450e83a7d32b6aeb5014e9e6b00a6423900251c
turbo-cache-controlno-preview
go-importgithub.com/codcodog/Blog git https://github.com/codcodog/Blog.git
octolytics-dimension-user_id18098145
octolytics-dimension-user_logincodcodog
octolytics-dimension-repository_id75478736
octolytics-dimension-repository_nwocodcodog/Blog
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id75478736
octolytics-dimension-repository_network_root_nwocodcodog/Blog
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
releaseae90d426644ca15e89bacceb72e51f4e9dbf85f7
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/codcodog/Blog/issues/124#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fcodcodog%2FBlog%2Fissues%2F124
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fcodcodog%2FBlog%2Fissues%2F124
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=codcodog%2FBlog
Reloadhttps://github.com/codcodog/Blog/issues/124
Reloadhttps://github.com/codcodog/Blog/issues/124
Reloadhttps://github.com/codcodog/Blog/issues/124
codcodog https://github.com/codcodog
Bloghttps://github.com/codcodog/Blog
Notifications https://github.com/login?return_to=%2Fcodcodog%2FBlog
Fork 1 https://github.com/login?return_to=%2Fcodcodog%2FBlog
Star 20 https://github.com/login?return_to=%2Fcodcodog%2FBlog
Code https://github.com/codcodog/Blog
Issues 135 https://github.com/codcodog/Blog/issues
Pull requests 0 https://github.com/codcodog/Blog/pulls
Actions https://github.com/codcodog/Blog/actions
Wiki https://github.com/codcodog/Blog/wiki
Security and quality 0 https://github.com/codcodog/Blog/security
Insights https://github.com/codcodog/Blog/pulse
Code https://github.com/codcodog/Blog
Issues https://github.com/codcodog/Blog/issues
Pull requests https://github.com/codcodog/Blog/pulls
Actions https://github.com/codcodog/Blog/actions
Wiki https://github.com/codcodog/Blog/wiki
Security and quality https://github.com/codcodog/Blog/security
Insights https://github.com/codcodog/Blog/pulse
slice 的问题https://github.com/codcodog/Blog/issues/124#top
Golanghttps://github.com/codcodog/Blog/issues?q=state%3Aopen%20label%3A%22Golang%22
https://github.com/codcodog
codcodoghttps://github.com/codcodog
on Oct 28, 2020https://github.com/codcodog/Blog/issues/124#issue-731471272
how-to-append-to-a-slice-pointer-receiverhttps://stackoverflow.com/questions/36854408/how-to-append-to-a-slice-pointer-receiver/36854446
深度解密Go语言之Slicehttps://www.cnblogs.com/qcrao-2018/p/10631989.html
Golanghttps://github.com/codcodog/Blog/issues?q=state%3Aopen%20label%3A%22Golang%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.